【问题标题】:How to invoke arrow functions on a superclass with `super` in subclass [duplicate]如何在子类中使用“super”在超类上调用箭头函数[重复]
【发布时间】:2019-12-24 22:52:00
【问题描述】:

您似乎无法在子类中使用super.methodName() 调用超类箭头函数:

class Parent {
  constructor() {
    console.log('in `Parent` constructor')
  }
  parentArrow = () => {
    console.log('parentArrowFn')
  }
  parentMethod() {
    console.log('parentMethod')
  }
}

class Child extends Parent {
  constructor() {
    super()
    console.log('in `Child` constructor')
  }
  childMethod() {
    console.log('childMethod')
    super.parentMethod() // works
    super.parentArrow() // Error
  }
}

(new Child()).childMethod();

产生错误:

Uncaught TypeError: (intermediate value).parentArrow is not a function
    at Child.childMethod (<anonymous>:21:15)
    at <anonymous>:1:7

有什么方法可以防止这种情况发生,以便我可以在父类中使用箭头函数,同时确保它们可以通过子类中的super 访问?

【问题讨论】:

  • 您必须使用super 还是this 也是一个选项? (它适用于this
  • 这里为什么需要super?如果您改用this.,这两个示例都可以正常工作。
  • 另外,在方法中使用箭头函数是不寻常的,因为它们不能使用this
  • @KevinB 我对此一无所知。如果是并且已经得到充分回答,也许将其标记为重复?
  • @Barmar 我使用带有 transform-class-properties 插件的箭头函数来避免在反应类的构造函数中绑定方法。我认为这很常见,不是吗?

标签: javascript class inheritance ecmascript-6 super


【解决方案1】:

es6 类中的公共字段或“类实例字段”尚未在所有环境中本机支持,即使您需要通过 this 引用而不是 super 来调用它,因为它变成了 instance 属性而不是 prototype 上的属性:

class Parent {
  constructor() {
    console.log('in `Parent` constructor')
  }   
  parentArrow = () => {
      console.log('parentArrowFn')
  }
  parentMethod() {
    console.log('parentMethod')
  }
}

class Child extends Parent {
  constructor() {
    super()
    console.log('in `Child` constructor')
  }
  childMethod() {
    console.log('childMethod')
    super.parentMethod() // works
    this.parentArrow() // Calls parentArrow 
  } 
}
new Child().childMethod();

需要使用this 而不是super 调用箭头函数是因为当使用箭头函数作为方法时,parentArrow 被添加为 instance 的属性而不是prototypesuper 用于调用原型上声明的方法。

当您在类中声明箭头函数时,您的代码可以转换为以下代码:

constructor() {
   console.log('in `Parent` constructor');
   // becomes an instance property
   this.parentArrow = () => { <----
     console.log('parentArrowFn') |
   }                              |
}                                 |
parentArrow = () => {          ----
   console.log('parentArrowFn')
}

【讨论】:

  • 因为在 Child 构造函数没有完全完成之前没有定义 parentArrow 属性。 错误!根据提议,类字段在构造函数中的代码运行之前运行。这也不是时间问题,因为 childMethod 是在构造完成后调用的
  • @JonasWilms 改写并更正了我的答案。
猜你喜欢
  • 2014-06-06
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 2017-04-01
相关资源
最近更新 更多