Search code examples
javascriptprototypal-inheritanceprototype-programming

About the prototype object and it's role in Javascript inheritance


I have only just started messing up with Javascript inheritance and can't get my hed round this one:

If I run this code:

function Foo(y) {
    this.y = y;
}

Foo.prototype.x = 1;

var Bar1 = new Foo(2);
var Bar2 = new Foo(3);

I expect to have the following "structure" in memory: enter image description here I messed up in the graphic, Bar2 obviously has a value of "3" for its property "y"

And happily enough, I can confirm that, by running this code:

console.log("Prototype - x: ", Foo.prototype.x, " y: ", Foo.prototype.y);
console.log("Bar1 - x: ", Bar1.x, " y: ", Bar1.y);
console.log("Bar2 - x: ", Bar2.x, " y: ", Bar2.y);

which prints:

Prototype - x: 1 y: undefined
Bar1 - x: 1 y: 2
Bar2 - x: 1 y: 3

Correct me if I'm wrong but what is happening there is that when I try to access the property x in the Bar1 and Bar2 objects, as those objects don't localy have a property called x, I'm getting that property from the next object in the prototype chain; i.e. the one whose reference they store in their "_ proto _" property.

Now is when I get lost, because if I after that code I alter the value of x like this:

Bar1.x = 10;

when I now run

console.log("Prototype - x: ", Foo.prototype.x, " y: ", Foo.prototype.y);
console.log("Bar1 - x: ", Bar1.x, " y: ", Bar1.y);
console.log("Bar2 - x: ", Bar2.x, " y: ", Bar2.y);

what I'am getting is

Prototype - x: 1 y: undefined
Bar1 - x: 10 y: 2
Bar2 - x: 1 y: 3

instead of what I would expect :

Prototype - x: 10 y: undefined
Bar1 - x: 10 y: 2
Bar2 - x: 10 y: 3

At that moment I could only explain that by assuming that each object was creating a copy of the Foo.prototype object, but if I run this

console.log(Object.is(Foo.prototype, Bar1.__proto__), Object.is(Bar1.__proto__, Bar2.__proto__));

I get true true, so both Bar1, Bar2 are accesing the same object.

Why is Bar1 then showing a different value for x if they are both getting it from the same object?


Solution

  • This line:

    Bar1.x = 10;
    

    does not change the value of x in the prototype. Instead it creates a new property (x) for Bar1 and assigns the value of 10 to it. Bar1 therefore no longer inherits x from its prototype as it now has its own property x.

    Bar2 still does, which is why it still matches the prototype value.