ES6 super()在构造函数中实际做了什么? [英] ES6 What does super() actually do in constructor function?

查看:227
本文介绍了ES6 super()在构造函数中实际做了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


Hola,amigos。我有这个小类继承结构

! Hola, amigos. I have this little class inheritance structure

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');

它编译为这个jsfiddle

我以愚蠢的方式了解es6的工作原理。
但是有人可以解释它在es5的引擎盖下是如何工作的。
以更简单的形式。

I get how it works in es6 in a silly way. But could somebody explain how does it work under the hood in es5. In a simpler form.

推荐答案

super(...); 基本上是的糖,这是新的ParentConstructor(...); 。其中 ParentConstructor 是扩展类, this = 的初始化关键字(好吧,鉴于这是禁止的语法,它有点多糖)。实际上它将继承适当的 new.target.prototype 而不是 ParentConstructor.prototype ,就像从 new 那样。所以不,它在引擎盖下如何工作根本不能与ES5相比,这实际上是ES6类中的一个新功能(最终使我们能够正确地对内置类进行子类化)。

super(…); is basically sugar for this = new ParentConstructor(…);. Where ParentConstructor is the extended class, and this = is the initialisation of the this keyword (well, given that that's forbidden syntax, there's a bit more than sugar to it). And actually it will inherit from the proper new.target.prototype instead of ParentConstructor.prototype like it would from new. So no, how it works under the hood does not compare to ES5 at all, this is really a new feature in ES6 classes (and finally enables us to properly subclass builtins).

这篇关于ES6 super()在构造函数中实际做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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