【发布时间】: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