类继承中未找到Javascript超级方法错误

问题描述 投票:0回答:2

考虑以下代码:

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
方法的正确方法是什么?

javascript class
2个回答
0
投票

它不是类上的方法,而是一个类属性,它是一个函数和一个箭头函数

类上的箭头函数很少有意义,因为它们没有

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!");

0
投票
  1. 在构造函数中使用
    super
    之前,您应该先调用
    this
  2. 您不能像使用
    super
    那样将
    whoAmI()
    与对象的 OWN 属性一起使用。
    super
    的方法应该位于类的原型中,并通过
    method(){}
    语法
  3. 作为类方法完成

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!");

© www.soinside.com 2019 - 2024. All rights reserved.