鉴于:
function A(name) {
this.name = name;
}
Run Code Online (Sandbox Code Playgroud)
是:
var a1 = new A("A1");
Run Code Online (Sandbox Code Playgroud)
完全等同于:
var a1 = {};
A.call(a1, "A1");
a1.__proto__ = A.prototype;
Run Code Online (Sandbox Code Playgroud)
?
谢谢
那么,问题__proto__是非标准(链接)并且不受所有实现的支持.:-)除此之外,constructor属性(链接)将无法正确设置,您可能必须自己这样做.另外,我认为在调用构造函数之前最好先设置原型.所以:
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
Run Code Online (Sandbox Code Playgroud)
不过,它至少在支持的实现方面很接近__proto__.我不会赌它完全相同.值得拥有的ECMAScript第5版规范的一个阅读更多的细节,特别是第11.2.2节" 的new运营商 "和13.2.2" [建设] ".
某些不支持的实现__proto__可能支持Object.create第5版规范(第15.2.3.5节)定义的新功能,该功能允许您使用特定原型创建对象.在支持的实现中Object.create,代码创建a1将如下所示:
var a1 = Object.create(A.prototype);
a1.constructor = A;
A.call(a1, "A1");
Run Code Online (Sandbox Code Playgroud)
滚动起来,然后:
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");
Run Code Online (Sandbox Code Playgroud)
......但是这完全没有经过测试,而且,我不会指望它完全相同,除非确实非常仔细地阅读规范.
当然,只要有可能,如果您正在处理构造函数,我建议您以正常方式使用它.先进的工具,如__proto__和Object.create是做纯原型继承(不需要构造函数)是有用的,但.
| 归档时间: |
|
| 查看次数: |
236 次 |
| 最近记录: |