Search code examples
javascriptinheritanceprototypejavascript-objects

What happens to the property inherited from base object when later that property of derived object is set again?


Here Object.create() is used for inheritance.

The JavaScript code:

var x = {
  a: 5, 
  foo: function() {
    return this.a * this.a;
  }
};

var o = Object.create(x);

console.log('\'x\':', x);
console.log('Object \'o\':', o);
console.log('Property \'o.a\':', o.a);
console.log('Method \'o.foo()\':', o.foo());

o.a = 7;
console.log('-----After setting o.a directly-----');

console.log('Object \'o\':', o);
console.log('Property \'o.a\':', o.a);
console.log('Method \'o.foo()\':', o.foo());

The output for above code is :

'x': { a: 5, foo: [Function: foo] }
Object 'o': {}
              __proto__: 
                  a: 5
                  foo: ƒ ()
                  __proto__: Object

Property 'o.a': 5
Method 'o.foo()': 25

-----After setting o.a directly-----

Object 'o': {a: 7}
              a: 7
              __proto__: 
                a: 5
                foo: ƒ ()
                __proto__: Object

Property 'o.a': 7
Method 'o.foo()': 49

So at first value a and function foo() are derived from x object to o object so they are in prototype of object o.

But later when I set the value of a in object o, the object has a new property a:7 as well as a:5 is still present in prototype of object o and strange thing is function foo() is returning 49(7*7) instead of 25(5*5)**, how is this possible?

EDIT: The code was run in Google Chrome's console and the output format is copied from there


Solution

  • This behavior is well-documented in the spec itself

    In other words, first the object mentioned directly is examined for such a property; if that object contains the named property, that is the property to which the reference refers; if that object does not contain the named property, the prototype for that object is examined next; and so on.

    So, when o didn't have its own a property, then its prototype was examined for the presence of that property.

    But when a become the own-property of o, it was picked up directly without going to its prototype chain.