I’m a beginner in Javascript, and having hard times trying to understand the relationship between constructor and prototype properties.
I know that Prototype object has a constructor property that points to constructor function. And the constructor function has a prototype property that points back to the prototype object.
Here’s a code i’m trying to understand with (my questions are commented in the code) :
function Car(){};
var myCar = new Car();
console.log(Object.getPrototypeOf(myCar)); //why this prints "Car" Object ? isn't it the constructor not the prototype object ? why the prototype object is not printed ?
var Vehicle = {
getName : function(){
return "hello";
}
};
Car.prototype = Vehicle ; //I'm trying to change the prototype property in the constructor to "Vehicle" Object is that done right ?
console.log(Object.getPrototypeOf(myCar).getName()); //Why am i getting getName() function does not exist ?
That’s just how Chrome (or the browser you use) names the object. If you have a close look at the properties, it really is
Car.prototype:You cannot change the prototype of an existing object, you can only extend it. Setting
Car.prototype = Vehicle;will only change the prototype for future instances ofCar, the existing ones will still refer to the original prototype object, which doesn’t have agetNameproperty:This really does not have anything to do with prototypes, but just how assignment and references work in JavaScript. Imagine I have the following object:
and assume I assign
foo.barto a property of an other object:Setting
foo.barto some other value now, likefoo.bar = {}, won’t change the value ofbaz.xyz, it will still refer to the previous object.Only extending the original object (extending the prototype), or changing its properties will have an effect, since both,
foo.barandbaz.xyzrefer to the same object: