Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't really understand constructor and prototype relationship in Javascript

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 ?
like image 695
Rafael Adel Avatar asked Sep 13 '26 05:09

Rafael Adel


1 Answers

why this prints "Car" Object ? isn't it the constructor not the prototype object ? why the prototype object is not printed ?

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:

enter image description here

I'm trying to change the prototype property in the constructor to "Vehicle" Object is that done right ?

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 of Car, the existing ones will still refer to the original prototype object, which doesn't have a getName property:

// create a new instance after setting the new prototype
var myCar2 = new Car();
// yields false
console.log(Object.getPrototypeOf(myCar) === Object.getPrototypeOf(myCar2)); 

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:

var foo = {
    bar: {
        answer: 42
    }
};

and assume I assign foo.bar to a property of an other object:

var baz = {};
baz.xyz = foo.bar;

Setting foo.bar to some other value now, like foo.bar = {}, won't change the value of baz.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.bar and baz.xyz refer to the same object:

foo.bar.answer = 21;
console.log(baz.xyz.answer); // shows 21
// console.log(foo.bar === baz.xyz); // yields true
like image 72
Felix Kling Avatar answered Sep 14 '26 19:09

Felix Kling



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!