考虑以下父类(super class)和扩展它的子类:
class SuperClass {
constructor(name){
this.name = name;
}
sayName = () => {
alert(this.name);
}
}
class SubClass extends SuperClass {
constructor(name){
super(name);
}
sayName = () => {
super.sayName();
document.getElementsByTagName('body')[0].innerHTML = this.name;
}
}
let B = new SubClass('Noam Chomsky');
B.sayName();
在此示例中,函数 sayName
在两个类定义中都被写为箭头函数。当我调用 B.sayName()
时,我收到一条错误消息:
'super' outside of function or class
JSFiddle demonstrating the error (查看控制台)
但是,如果我重写类定义以不使用箭头函数,一切正常并且我不会收到错误:
class SuperClass {
constructor(name){
this.name = name;
}
sayName() {
alert(this.name);
}
}
class SubClass extends SuperClass {
constructor(name){
super(name);
}
sayName() {
super.sayName();
document.getElementsByTagName('body')[0].innerHTML = this.name;
}
}
let B = new SubClass('Noam Chomsky');
B.sayName();
JSFiddle demonstrating that it works fine
有人可以解释为什么我在此处使用箭头函数时会出现此错误吗?
最佳答案
区别在于
sayName1 = () => {
alert(this.name);
}
是函数类型的属性,而
sayName2() {
alert(this.name);
}
是一种方法。 ES 类以完全不同的方式处理方法和属性。方法存在于类原型(prototype)上,而属性被分配给每个实例。你不能通过 super.sayName1
访问父级的 sayName1
因为它不在你父级的类中,它只在实例对象上并且可以通过 访问instance.sayName1
.
此外,来自 ECMAScript® 2015 Language Specification :
An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment... An ArrowFunction that references super is always contained within a non-ArrowFunction and the necessary state to implement super is accessible via the scope that is captured by the function object of the ArrowFunction.
关于javascript - ES6箭头函数触发 "' super'outside of function or class"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46869503/