Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have the following code;

var A = {a:10};
var B = {b:20};
B.prototype = A;
alert(B.a);

I am getting undefined for B.a . Am I doing something wrong? How do I set the prototype for object literal ?

I know how to do for Constructor object. So the following code works perfect

function A(){this.a=10}
function B(){this.b=20}
B.prototype = new A();
b = new B;
alert(b.a);

How do I do it for object literal ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
242 views
Welcome To Ask or Share your Answers For Others

1 Answer

Objects inherit from their constructor's prototype property, not their own. The constructor's prototype is assigned to the internal [[Prototype]] property that is available in some browsers as the __proto__ property.

So for b to inherit from a, you need to put a on b's inheritance chain, e.g.

Classic prototype inheritance:

var a = {a: 'a'};
function B(){}
B.prototype = a;

var b = new B();
alert(b.a); // a

Using ES5 Object.create:

var a = {a: 'a'};
var b = Object.create(a);

alert(b.a); // a

Using Mozilla __proto__:

var a = {a: 'a'};
var b = {};
b.__proto__ = a;

alert(b.a); // a

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...