我在 JavaScript 中看到一些奇怪的行为,我想知道是什么原因造成的。我有以下代码,它使用工厂模式创建两种类型的车辆,汽车和卡车。
$(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);
});
当我写到控制台时,如果我检查我实例化的车辆类型是否是正确的类型,我注意到这console.log(movingTruck instanceof Truck)
是真的,但console.log('movingTruck is instance of Truck: ' + movingTruck instanceof Truck)
会是假的。这是为什么?小提琴