设置Object Literal的原型 [英] Setting prototype for Object Literal
问题描述
假设我有以下代码;
var A = {a:10};
var B = {b:20};
B.prototype = A;
alert(B.a);
我对B.a的定义不明确。
我做错了吗?如何设置对象文字的原型?
I am getting undefined for B.a . Am I doing something wrong? How do I set the prototype for object literal ?
我知道如何为Constructor对象做。所以下面的代码是完美的
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 ?
推荐答案
对象继承自构造函数的原型属性,而不是自己的属性。构造函数的原型被分配给内部 [[原型]]
属性在某些浏览器中可用作 __ proto __
property。
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.
所以 b
从 a
继承,你需要在<$ c $上放 a
c> b 的继承链,例如
So for b
to inherit from a
, you need to put a
on b
's inheritance chain, e.g.
经典原型继承:
var a = {a: 'a'};
function B(){}
B.prototype = a;
var b = new B();
alert(b.a); // a
使用ES5 Object.create:
Using ES5 Object.create:
var a = {a: 'a'};
var b = Object.create(a);
alert(b.a); // a
使用Mozilla __ proto __
:
Using Mozilla __proto__
:
var a = {a: 'a'};
var b = {};
b.__proto__ = a;
alert(b.a); // a
这篇关于设置Object Literal的原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!