ES6 super() 在构造函数中实际上做了什么?
ES6 What does super() actually do in constructor function?
!
你好,朋友们。我有这个小小的 class 继承结构
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');
我以一种愚蠢的方式了解它在 es6 中的工作方式。
但是有人可以解释一下它在 es5 中是如何工作的吗?
更简单的形式。
super(…);
基本上是 this = new ParentConstructor(…);
的糖。其中 ParentConstructor
是扩展的 class,this =
是 this
关键字的初始化(好吧,考虑到这是被禁止的语法,它不仅仅是糖分) .实际上它将继承自正确的 ,而不是像继承自 new
的 ParentConstructor.prototype
。所以不,它在引擎盖下的工作方式根本无法与 ES5 相提并论,这确实是 ES6 classes 中的一个新功能(最终使我们能够正确地 subclass 内置函数)。
! 你好,朋友们。我有这个小小的 class 继承结构
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');
我以一种愚蠢的方式了解它在 es6 中的工作方式。 但是有人可以解释一下它在 es5 中是如何工作的吗? 更简单的形式。
super(…);
基本上是 this = new ParentConstructor(…);
的糖。其中 ParentConstructor
是扩展的 class,this =
是 this
关键字的初始化(好吧,考虑到这是被禁止的语法,它不仅仅是糖分) .实际上它将继承自正确的 new
的 ParentConstructor.prototype
。所以不,它在引擎盖下的工作方式根本无法与 ES5 相提并论,这确实是 ES6 classes 中的一个新功能(最终使我们能够正确地 subclass 内置函数)。