Mike Mike - 3 months ago 12
Javascript Question

JavaScript: instanceof operator unexpected result

I've recently discovered prototypes for myself, and would be happy to get some help with figuring out the thing:

Code example 1:

"use strict";

var Car = function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
return obj;
};

Car.prototype.move = function() {
this.loc++;
return this.loc;
};

var bmw = Car(6);

console.log( bmw instanceof Car );


Code example 2:

"use strict";

var Car = {
"makeCar": function(loc) {
var obj = Object.create(Car.prototype);
obj.loc = loc;
return obj;
},
"prototype": {
"move": function() {
this.loc++;
return this.loc;
}
}
};

var bmw = Car.makeCar(6);

console.log( bmw instanceof Car.makeCar );


I wrote example 2, cause I want to keep methods for Car object inside the object itself. I'm not sure if it can be done, but it's working so far, except the "instanceof" operator.

In the first example it will log "true", but in second it will log "false" and I've no idea where am I wrong, so counting on your help, thank you.

Answer

console.log( bmw instanceof Car.makeCar ); yields false

…because Car.makeCar does not have the instances' prototype on its .prototype property. The instanceof expression is equivalent to Car.makeCar.prototype.isPrototypeOf(bmw). To make it work, you'd need to set

Car.makeCar.prototype = Car.prototype;

but that's weird. Just keep the standard patterns. If you want to declare your methods in a structural unit together with the constructor, wrap everything in an IEFE like here or just use an ES6 class

Comments