[英]Why super() should come before accessing this
In ES6 class constructor, why super()
should come before accessing this
, if not there's an error thrown: Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
.在 ES6 类构造函数中,为什么
super()
应该在访问this
之前出现,否则会抛出错误: Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
。
But before and after calling super()
, this
always reference the created object.但是在调用
super()
之前和之后, this
总是引用创建的对象。 So Why we have to call super()
before accessing this
, maybe to prevent from accessing uninitialized parent member?那么为什么我们必须在访问
this
之前调用super()
,也许是为了防止访问未初始化的父成员? Is there more ideas about that?有没有更多的想法?
From here , refer to the below code.从这里,参考下面的代码。 Here
super()
is called to avoid duplicating the constructor parts' that are common between Rectangle
and Square
.这里调用
super()
是为了避免复制Rectangle
和Square
之间常见的构造函数部分。
class Rectangle {
constructor(height, width) {
this.name = 'Rectangle';
this.height = height;
this.width = width;
}
sayName() {
console.log('Hi, I am a ', this.name + '.');
}
get area() {
return this.height * this.width;
}
set area(value) {
this._area = value;
}
}
class Square extends Rectangle {
constructor(length) {
this.height; // ReferenceError, super needs to be called first!
// Here, it calls the parent class's constructor with lengths
// provided for the Rectangle's width and height
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
this.name = 'Square';
}
}
Now, why calling this
before super()
will result in a ReferenceError
?现在,为什么在
super()
之前调用this
会导致ReferenceError
? Well, there is no straightforward answer to that question.嗯,这个问题没有直接的答案。 However, the intuition is that this requirement ensures that a superclass constructor has had a chance to initialize itself before the allocated object is used.
然而,直觉是这个要求确保超类构造函数有机会在使用分配的对象之前初始化自己。 This means that if you write a base class, you don't have to worry about subclasses accidentally forgetting to call
super()
but still invoking methods that assume that initialization has taken place.这意味着如果您编写基类,您不必担心子类会意外忘记调用
super()
但仍然调用假定已进行初始化的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.