super() on class that extends
Allen Wirfs-Brock
allen at wirfs-brock.com
Sat Apr 11 02:46:48 UTC 2015
> On Apr 10, 2015, at 8:06 PM, Axel Rauschmayer <axel at rauschma.de> wrote:
>
> ...
> If you do not call `super()`, you only get into trouble if you access `this` in some manner. Two examples:
>
> ...
>
> Therefore, there are two ways to avoid typing super-constructor calls.
>
> First, you can avoid accessing `this` by explicitly returning an object from the derived class constructor. However, this is not what you want, because the object created via `new B()` does not inherit `A`’s methods.
>
> ```js
> // Base class
> class A {
> constructor() {}
> }
> // Derived class
> class B extends A {
> constructor() {
> // No super-constructor call here!
>
> return {}; // must be an object
> }
> }
> ```
>
> Second, you can let JavaScript create default constructors for you:
>
> ```js
> // Base class
> class A {
> }
> // Derived class
> class B extends A {
> }
> ```
>
> This code is equivalent to:
>
> ```js
> // Base class
> class A {
> constructor() {}
> }
> // Derived class
> class B extends A {
> constructor(...args) {
> super(...args);
> }
> }
> ```
or third, about the super class to make sure that you correctly initialize the instance to work with inherited methods:
‘’’js
class B extends A {
constructor(…args) {
let newObj = Reflect.construct(Object, args, this.target);
newObj.prop = something;
return newObj;
}
}
```
Allen
More information about the es-discuss
mailing list