instanceof检查JavaScript工厂模式

时间:2013-10-24 14:40:11

标签: javascript design-patterns

我在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)会是假的。这是为什么? Fiddle

1 个答案:

答案 0 :(得分:4)

操作员优先级很简单。 尝试改为

console.log('movingTruck is instance of Truck: ' + (movingTruck instanceof Truck));