有没有一种方法可以确定继承类是否费心super()
在JavaScript中调用?
function A() {
A.prototype.isInitialized = function() {
// what can be checked to see if B bothered to called super()
}
}
class B extends A {
//constructor() {
// didn't call super()
//}
}
假设B没有自己的构造函数。它是否仅使用A的构造函数,从而在默认情况下有效地调用了super?
如果不同时调用A的构造函数,则无法创建B的实例(除非您不使用将为您创建的对象,而是返回另一个对象,请参见下文)。
如果您没有为类B指定构造函数,那么将为您创建一个看起来像这样的构造函数(在您的情况下,没有参数):
constructor(...args) {
super(...args);
}
如果为B显式创建一个构造函数,并且不返回任何对象,则必须super
在其中调用它,否则无法创建B的实例。以下将产生错误:
function A() {
console.log('hi');
}
class B extends A {
constructor() {
// no call to super is made
}
}
var b = new B(); // Reference Error: `this` is not defined
但是,如果您忽略了将为您创建的对象(上下文,this
),不引用this
并返回另一个对象,则不会调用父级的构造函数:
function A() {
console.log('hi');
this.isInitialised = true;
}
class B extends A {
constructor() {
return Object.create(B.prototype);
}
}
var b = new B();
console.log(b instanceof B, b instanceof A, b.isInitialised); // true, true, undefined
在这里,我们Object.create
用来创建B的原型的实例,它是A的实例,但是不会执行A的构造函数。查看输出以解释结果。
因此,无论您是否在B上定义构造函数,在所有不返回对象的有效情况下,都会调用A的构造函数。
return
在B的构造函数中使用时,可以创建一个对象,该对象仍然是A的实例,但是不调用其构造函数。您可以在A实例中使用属性来指示构造函数是否运行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句