4

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.

4
  • 1
    Yes..just check the console here jsfiddle.net/sandenay/azjmxasu Commented Oct 14, 2015 at 5:45
  • You can see a and b on the __proto__ property of p Commented Oct 14, 2015 at 5:45
  • Yes, it's the protootype chain. You can avoid it by shadowing a and b: p.a = p.b = 5; p.f() === 10 Commented Oct 14, 2015 at 5:46
  • To avoid that you can use var p = jQuery.extend({},o); in jQuery. Commented Oct 14, 2015 at 5:48

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.