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.
Car.makeCaris a function not a Car object.instanceoftests whether the object's prototype chain contains the prototype of the constructor.bmw's prototype chain containsCar, notCar.makeCar.bmw instanceof Cardoes still work, because you're still creating the instance to inherit fromCar.prototypeCarwould need to be a constructor for that to work.Car.makeCaris not a constructor and does not have the instances' prototype on its.prototypeproperty, so that doesn't work either.