Beroza Paul
Beroza Paul

Reputation: 2117

Why both the function calls return the same value?

See the code segment below:

var o = {f:function(){ return this.a + this.b; }};
var p = Object.create(o);
o.a = 10;
o.b = 20;

console.log(o.f());  // output: 30
console.log(p.f());  // output: 30

The object p doesn't have property p.a and p.b then how p.f() return output 30. Is that prototype chain? Could anyone explain this? Thanks in advance.

Upvotes: 4

Views: 73

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388446

Here o is the prototype of the p object, so all the propeties of o is available in p.

So when you call p.f(), you will get the values assigned to o in this.a and this.b

Upvotes: 9

Related Questions