javascript - ES6 super() 在构造函数中实际上做了什么?

标签 javascript class constructor ecmascript-6 super

! 你好, friend 们。我有这个小类继承结构

class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        return '(' + this.x + ', ' + this.y + ')';
    }
}

class ColorPoint extends Point {
    constructor(x, y, color) {
        super(x, y); 
        this.color = color;
    }
    toString() {
        return super.toString() + ' in ' + this.color; 
    }
}

let newObj = new ColorPoint(25, 8, 'green');

它编译为 this jsfiddle

我以一种愚蠢的方式了解它在 es6 中的工作方式。 但是有人可以解释一下它在 es5 中是如何工作的吗? 以更简单的形式。

最佳答案

super(…); 基本上是 this = new ParentConstructor(…); 的糖。其中 ParentConstructor 是扩展类,this =this 关键字的初始化(好吧,考虑到这是被禁止的语法,有一点比糖还多)。实际上它将继承自适当的 new.target.prototype而不是像 new 那样的 ParentConstructor.prototype。所以不,它在幕后的工作方式根本无法与 ES5 相提并论,这确实是 ES6 类中的一个新特性(最终使我们能够正确地对内置函数进行子类化)。

关于javascript - ES6 super() 在构造函数中实际上做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42582147/

相关文章:

javascript - 如何在 phonegap 中打开系统文件资源管理器

javascript - 是否可以通过 Node JS 在几分钟内插入/更新 MySQL 中的 8,000,00 条记录

javascript - document.location.href 不更新共享点中的 onkeypress

java - 如何通过 Java 反射从父类中获取嵌套类

python - 如何在没有 __dict__ 的情况下创建类对象

html - 保存富字段后,Microsoft Sharepoint 将 "External Class"添加到我的 CSS

objective-c - Cocoa Objective-C 初始化异常

javascript - jQuery选择div问题

c++ - 仅对 C++ 中的空私有(private)构造函数使用声明是否正确?

java - super() 不让我用参数调用 super 构造函数