stackoverflow
stackoverflow

Reputation: 1587

Why super() returns the newly created object in es6?

As far as I know

The super([arguments]) keyword calls the parent constructor

Having these basic classes:

class X{
    constructor(){
       return 'x'; // doesn't matter when calling super()
    }
}
class Z extends X{
    constructor(){
        console.log('This will return the newly created object invoked by new keyword', super())
    }
}
new Z; // Z {}

why super() return the brand new Z object?

Upvotes: 0

Views: 34

Answers (1)

Yury Tarabanko
Yury Tarabanko

Reputation: 45121

You can't return primitive types from constructor.

class X{
    constructor(){
       // to set correct prototype
       return Object.setPrototypeOf(new String("x"), new.target.prototype); 
       // or 
       // return new String('x') just to show you could return any object
    }
}
class Z extends X{
    constructor(){
        console.log('This will return the newly created object invoked by new keyword', super())
    }
}
console.log(new Z); // Z {}

Upvotes: 2

Related Questions