这两种在JavaScript中构造对象的方法是等效的吗?
鉴于: 是: 完全等同于:这两种在JavaScript中构造对象的方法是等效的吗?,javascript,Javascript,鉴于: 是: 完全等同于: var a1 = new A("A1"); ? 谢谢好吧,有一个问题是,\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>是非标准的(),并非所有实现都支持。:-)除此之外,构造函数属性()将无法正确设置,您可能必须自己进行设置。另外,我认为最好在调用构造函数之前设置原型。因此: var a1 = {}; A.call(a1, "A1"); a1.__proto__ = A.prototype; 把它
var a1 = new A("A1");
?
谢谢好吧,有一个问题是,
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>是非标准的(),并非所有实现都支持。:-)除此之外,构造函数
属性()将无法正确设置,您可能必须自己进行设置。另外,我认为最好在调用构造函数之前设置原型。因此:
var a1 = {};
A.call(a1, "A1");
a1.__proto__ = A.prototype;
把它卷起来,然后:
var a1 = Object.create(A.prototype);
a1.constructor = A;
A.call(a1, "A1");
…但这是完全未经测试的,而且,我不会指望它完全相同,除非仔细阅读规范
当然,只要有可能,如果您处理的是构造函数,我建议您以正常方式使用它。高级工具,如\uuu proto\uu
和Object.create
对于执行纯原型继承非常有用(不需要构造函数)
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
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");