为什么 Javascript ES6 不能调用匿名超级函数?

Why can't Javascript ES6 call an anonymous super function?

请解释使用匿名函数的父子关系和使用class函数的区别? 在案例 1 中,一切都按预期工作。在情况 2 中,codepen 没有 return 任何结果。

//CASE 1
class Parent {
  constructor(name) {
    this.name = name;
  }

  exec() {
    console.log('name', this.name);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }

  exec() {
    super.exec();
    console.log('age', this.age);
  }
}

const c = new Child('ChildName', 31);
c.exec();

//writes Childname + 31 (expected behaviour)

//CASE 2
class Parent {
  constructor(name) {
    this.name = name;
  }

  exec = () => {
    console.log('name', this.name);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);
    this.age = age;
  }

  exec = () => {
    super.exec();
    console.log('age', this.age);
  }
}

const c = new Child('ChildName', 31);
c.exec();

//writes nothing. Seems to crash.

实例对象只有一个,一个对象上不能有两个同名的属性。你的 subclass 属性 覆盖了 superclass.

的 属性

此外,您无法通过 super 访问属性,因为 super 指的是 上层原型 ,并且不包含任何 属性 在你的第二种情况下(在你的第一种情况下它包含方法)。因此,super.execundefined,调用它会引发错误。

原型链如下所示:

 // Case 1
                                              - super ------------v
 { name: "ChildName", age: 31 } -> Child { exec() { ... } } -> Parent { exec() { ... } }


 // Case 2
                                  - super² --------------------v                   
 { name: "ChildName", age: 31, exec() { ... } } -> Child {} -> Parent {}

² 实例中的 super 指向 Parent 可能有点令人困惑,但那是因为 class 字段是 evaluated inside of a special initializer function, and that has Child as it's [[HomeObject]], not the instance, and as super refers to the [[HomeObject]]s prototype,它将引用Parent.