首页 > 解决方案 > 为什么 Javascript ES6 不能调用匿名超函数?

问题描述

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

//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.

标签: javascriptecmascript-6babeljsanonymous-functiones6-class

解决方案


只有一个实例对象,一个对象上不能有两个同名的属性。您的子类属性会覆盖超类的属性。

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

原型链如下所示:

 // 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,但这是因为类字段是在一个特殊的初始化函数内部评估的,并且它具有Child[[HomeObject]],而不是实例,并且super引用[[HomeObject]]s原型,会参考Parent


推荐阅读