2010-10-04 78 views

回答

6

嗯,有问题的是__proto__是非标准(link),而不是所有的实现支持。 :-)除此之外,constructor属性(link)设置不正确,你可能必须自己做。另外,我认为在调用构造函数之前,最好先设置原型。所以:

function A(name) { 
    this.name = name; 
} 

var a1 = {}; 
a1.__proto__ = A.prototype; 
a1.constructor = A; // <=== Added this bit 
A.call(a1, "A1"); // <=== Moved this down 

已经很接近了,不过,至少在支持__proto__实现。我不打赌完全一样。值得阅读ECMAScript第5版规范的更多细节,具体部分11.2.2“new运营商”和13.2.2“[[构造]]”。

不支持__proto__可以支持第5版规范(第15.2.3.5),它允许您与特定的原型创建一个对象定义的新Object.create功能有些实现。在支持Object.create实现,创造a1代码是这样的:

var a1 = Object.create(A.prototype); 
a1.constructor = A; 
A.call(a1, "A1"); 

滚动起来,则:

function A(name) { 
    this.name = name; 
} 

if (typeof Object.create === "function") { 
    a1 = Object.create(A.prototype); 
} 
else if ({}.__proto__) { 
    a1 = {}; 
    a1.__proto__ = A.prototype; 
} 
else { 
    /* Fail */ 
} 
a1.constructor = A; 
A.call(a1, "A1"); 

...但这是完全未经测试,并再次,我不会指望它是正好同样禁止一个非常接近的规范确实阅读。

只要有可能,当然,如果你正在处理构造函数,我建议以正常方式使用它。不过,像__proto__Object.create这样的高级工具对于做纯原型继承(不需要构造函数)非常有用。

+0

很棒的回答。谢谢。 – zod 2010-10-04 14:32:49