Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 770
Beroza Paul Avatar asked Jan 08 '23 09:01

Beroza Paul


1 Answers

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

like image 166
Arun P Johny Avatar answered Jan 09 '23 23:01

Arun P Johny