javascript - ES6箭头函数触发 "' super'outside of function or class"错误

标签 javascript ecmascript-6

考虑以下父类(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/

相关文章:

javascript - 如何在图像上添加标签。在 jquery 移动图像的四个 Angular

javascript - 在 AngularJS 中显示 JSON 数组中的键值

javascript - Webpack - 加载 block 0 失败

vue.js - 如何更改 v-slider 的大小?

javascript - 引用错误: chunks is not defined

javascript - 使用 Jquery 如何获取输入值来确定数据最小最大范围上的选择框值

path - ES6 如何解析导入路径,我们可以自定义其行为吗

javascript - 在 javascript 中使用 for of 循环迭代对象数组

javascript - 在 three.js 中需要一个带纹理的圆圈

javascript - 为 react 组件传递 Prop 的最佳方式