【问题标题】:Why can't Javascript ES6 call an anonymous super function? [duplicate]为什么 Javascript ES6 不能调用匿名超函数? [复制]
【发布时间】:2019-08-19 14:57:03
【问题描述】:

请解释一下使用匿名函数的父子关系和使用类函数的区别? 在案例 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.

【问题讨论】:

  • 如果你没有使用像 babel 之类的转译器,那么你目前正在做的事情将会失败,因为类属性 ATM 不能是箭头函数。只是尚未实施。
  • @kemicofa 会抛出一个 SyntaxError 虽然 ...
  • @kemicofa:我在我的主项目中使用 babel。也在 codepen 上使用 babel。
  • @JonasWilms 我正在 codepen 中测试这个。浏览器不会冻结,但不会产生结果(我假设 codepen 不想编译)

标签: javascript ecmascript-6 babeljs anonymous-function es6-class


【解决方案1】:

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

此外,您不能通过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 可能有点令人困惑,但那是因为类字段是evaluated inside of a special initializer function,并且有Child,因为它是[[HomeObject]],而不是例如,作为super refers to the [[HomeObject]]s prototype,它将引用Parent

【讨论】:

  • 那为什么 CASE 1 工作得很好?调用超级方法有效,但不适用于匿名函数。
  • 我对我最后的声明不太确定,我会重新阅读相关的规范部分,我很快就会回来
  • 更新:super 是词法解析的,就像this 一样,因此取决于如何为类字段创建闭包,这可以工作super.exec 将不过还是undefined
  • Update2:它确实有效。 According to the proposal 初始化程序在一个行为与构造函数()完全相同的函数内部执行,因此thissuper 都可以访问。还是不行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 1970-01-01
  • 1970-01-01
  • 2016-10-01
  • 2011-12-23
  • 2013-08-29
相关资源
最近更新 更多