为什么 Javascript ES6 不能调用匿名超级函数? [英] Why can't Javascript ES6 call an anonymous super function?

查看:24
本文介绍了为什么 Javascript ES6 不能调用匿名超级函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please explain the difference between using a parent-child relationship using anonymous functions and using class functions? In case 1 everything works as expected. In case 2, codepen does not return any results.

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

推荐答案

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

There is just one instance object, and there can't be two properties with the same name on one object. Your subclass property overrides the property of the superclass.

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

Additionally you can't access properties via super as super refers to the upper level prototype, and that does not contain any property in your second case (in your first case it contains the method). Therefore, super.exec is undefined, and calling that throws an error.

原型链如下所示:

 // 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]] 的原型,它将引用 Parent.

² It might be a bit confusing that super inside of the instance points to Parent, but that's because class fields are 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, it will refer to Parent.

这篇关于为什么 Javascript ES6 不能调用匿名超级函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆