I'm seeing some strange behavior in JavaScript and I'd like to know what's causing it. I've got the following code which uses the factory pattern to create two types of vehicles, cars and trucks.
$(document).ready(function () {
//car constructor
function Car(options) {
//defaults
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || " silver";
};
//truck constructor
function Truck(options) {
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
//define a skeleton vehicle factory
function VehicleFactory() { };
//default vehicleClarr is Car
VehicleFactory.prototype.vehicleClass = Car;
//our factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function (options) {
if (options.vehicleType === 'car') {
this.vehicleClass = Car;
}
else {
this.vehicleClass = Truck;
}
return new this.vehicleClass(options);
}
//create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle({
vehicleType: 'car',
color: 'yellow',
doors: 6
});
//true
console.log(car instanceof Car);
console.log('car: ' + car instanceof Car);
var movingTruck = carFactory.createVehicle({
vehicleType: 'truck',
state: 'like new',
color: 'red',
wheelSize: 'regular'
});
//true
console.log(movingTruck instanceof Truck);
//false?
console.log('movingTruck is instance of Truck: ' + movingTruck instanceof Truck);
});
When writing to the console if I check to see if the vehicle types I instantiated were of the correct types I noticed that console.log(movingTruck instanceof Truck) would be true
but console.log('movingTruck is instance of Truck: ' + movingTruck instanceof Truck) would be false. Why is that? Fiddle
createVehiclealways accepts the type to create, what's thevehicleClassproperty for? HavingcreateVehiclemodify the state of the factory looks off.