Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof check in JavaScript factory pattern

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

like image 619
wootscootinboogie Avatar asked Feb 27 '26 06:02

wootscootinboogie


1 Answers

It is a simple matter of operator priority. Try instead

console.log('movingTruck is instance of Truck: ' + (movingTruck instanceof Truck));
like image 192
hazerd Avatar answered Feb 28 '26 20:02

hazerd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!