我想知道是否可以通过自动使用父类(super class)的构造函数在 javascript 中实例化子类。
考虑一下(受 this other question here on SO 启发):
function A(prop) {
this.prop = prop;
}
A.prototype.whatAmI = function() {
console.log(
"I'm an instance of %s, my prop is %s",
this instanceof A1? "A1" : "A2",
this.prop
);
};
function A1() {
A.apply(this, arguments);
}
A1.prototype = new A();
A1.prototype.constructor = A1;
function A2() {
A.apply(this, arguments);
}
A2.prototype = new A();
A2.prototype.constructor = A2;
var a1 = new A1("foo").whatAmI(); //I'm an instance of A1, my prop is foo
var a2 = new A2("bar").whatAmI(); //I'm an instance of A2, my prop is bar
然而,引用this article ,在第一个示例中,我遇到了这行代码:
Cat.prototype.constructor = Cat;
//Otherwise instances of Cat would have a constructor of Mammal
我认为这正是我所需要的:A1
和 A2
的实例具有 A
的构造函数。不幸的是,注释掉 A1.prototype.constructor = A1
并清空 A1
的主体(同样适用于 A2
)不起作用:
function A1() {}
A1.prototype = new A();
function A2() {}
A2.prototype = new A();
var a1 = new A1("foo").whatAmI(); //I'm an instance of A1, my prop is undefined
var a2 = new A2("bar").whatAmI(); //I'm an instance of A2, my prop is undefined
最后,将 A
的构造函数更改为使用 arguments
对象而不是显式传递 prop
也没有效果:
function A() {
this.prop = arguments[0];
}
是否有可能通过对 prototype
属性进行一些修改来实现我想要的?
最佳答案
Cat.prototype.constructor = Cat; //Otherwise instances of Cat would have a constructor of Mammal
I thought that's exactly what I needed: that instances of A1 and A2 have the constructor of A.
不,他们不是这个意思。 A1
和 A2
函数是仍然是它们自己的被调用的构造函数,你不能改变它。
文章描述的问题是 .constructor
当您覆盖 A<i>X</i>.prototype
时,所有实例继承的属性指出它们的构造函数 不再有效.另见 What is the `constructor` property really used for? (和相关问题)。
Unfortunately commenting out
A1.prototype.constructor = A1
and emptying A1's body (same goes for A2) does not work.
通过清空 body ,它不再做任何事情。您仍然需要调用 A
明确地,你不会绕过那个。您可以做的是创建一个通用工厂,为 A
创建子类。没有做任何特别的事情,但我认为这不值得。
哦,别忘了:You should not use new
for creating prototypes !
subclass(parent) {
function Child() {
parent.apply(this, arguments);
}
Child.prototype = Object.create(parent.prototype);
Child.prototype.constructor = Child;
return Child;
}
function A(prop) {
this.prop = prop;
}
A.prototype.whatAmI = function() {
console.log(
"I'm an instance of %s, my prop is %s",
this instanceof A1? "A1" : "A2",
this.prop
);
};
var A1 = subclass(A),
A2 = subclass(A);
关于javascript - 在javascript中继承和使用父类(super class)的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25672688/