考虑以下代码:
class Parent {
constructor(name) {
this.name = name;
}
whoAmI = data => {
console.log("Parent whoAmI called. Parent name: " + this.name);
console.log(data);
};
}
class Child extends Parent {
constructor(childName, parentName) {
this.name = childName;
super(parentName);
}
whoAmI = data => {
console.log("Child whoAmI called. Parent name: " + this.name);
super.whoAmI(data);
};
}
let child = new Child("Dad", "Son");
child.whoAmI("Hello!");
我在
node
环境中收到以下错误:
return _get((_thisSuper = _assertThisInitialized(_this), _getPrototypeOf(Parent.prototype)), "whoAmI", _thisSuper).call(_thisSuper, data);
^
TypeError: Cannot read properties of undefined (reading 'call')
正如错误所述,未找到
super.whoAmI
,但我已经初始化了父类...不知道出了什么问题...
重写和调用
super.whoAmI
方法的正确方法是什么?
它不是类上的方法,而是一个类属性,它是一个函数和一个箭头函数。
类上的箭头函数很少有意义,因为它们没有
this
或 super
的概念。这解释了错误,因为当 super
是箭头函数时,调用 whoAmI
时,没有 whoAmI
。
你想要的可能是这样的:
class Parent {
constructor(name) {
this.name = name;
}
// Note the difference between whoAmI = (data) => and whoAmI(data) {
whoAmI(data) {
console.log("Parent whoAmI called. Parent name: " + this.name);
console.log(data);
};
}
class Child extends Parent {
constructor(childName, parentName) {
this.name = childName;
super(parentName);
}
// Note the difference between whoAmI = (data) => and whoAmI(data)
whoAmI(data) {
console.log("Child whoAmI called. Parent name: " + this.name);
super.whoAmI(data);
};
}
let child = new Child("Dad", "Son");
child.whoAmI("Hello!");
super
之前,您应该先调用 this
。super
那样将 whoAmI()
与对象的 OWN 属性一起使用。 super
的方法应该位于类的原型中,并通过 method(){}
语法class Parent {
constructor(name) {
this.name = name;
}
whoAmI( data) {
console.log("Parent whoAmI called. Parent name: " + this.name);
console.log(data);
};
}
class Child extends Parent {
constructor(childName, parentName) {
super(parentName);
this.name = childName;
}
whoAmI = data => {
console.log("Child whoAmI called. Parent name: " + this.name);
super.whoAmI(data);
};
}
let child = new Child("Dad", "Son");
child.whoAmI("Hello!");