! 你好, 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/