Reading Dr. Axel Rauschmayer's blog on ES6 classes, I understand that a derived class has the following default constructor when none is provided
constructor(...args) {
super(...args);
}
I also understand that if I want to use this
within a constructor I first need to call super
, otherwise this
will not yet be initialized (throwing a ReferenceError).
constructor(width, height) {
this.width = width; // ReferenceError
super(width, height);
this.height = height; // no error thrown
...
}
Is the following assumption then correct? (and if not, could you please explain the conditions under which I should explicitly call super
)
For derived classes, I only need to explicitly call super
when...
- I need to access
this
from within the constructor
- The superclass constructor requires different arguments then the derived class constructor
Are there other times when I should include a call to the superclass constructor?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…