简体   繁体   中英

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 .

But before and after calling super() , this always reference the created object. So Why we have to call super() before accessing this , maybe to prevent from accessing uninitialized parent member? 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 .

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 ? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM