Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - Setting prototype for Object Literal

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...