Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is new super.constructor a valid expression in JavaScript?

I would like to know if expressions of the form new super.SomeProperty are valid in JavaScript.

This question arose while working with code that behaves inconsistently across browsers like the example in the snippet below.

class Test {
    test() {
        return new super.constructor;
    }
}

console.log((new Test).test());

This prints an empty object in Firefox and Edge but throws a ReferenceError in Chrome and a SyntaxError in Safari. The error can be easily circumvented putting parentheses around super.constructor or using a variable, so it's not a real limitation, rather a matter of curiosity about the language itself. I checked the spec but couldn't find anything implying that an error should be thrown in this case, so it's likely that I'm missing something.

like image 231
GOTO 0 Avatar asked May 11 '18 09:05

GOTO 0


People also ask

What is super constructor in JavaScript?

The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.

Do you have to call super in constructor JavaScript?

In the constructor body of a derived class (with extends ), the super keyword may appear as a "function call" ( super(... args) ), which must be called before the this keyword is used, and before the constructor returns.

Is Super necessary in JavaScript?

The call to super() is required always. Try to write a valid ES6 constructor without super() .

What does super () do in JS?

The super keyword in JavaScript acts as a reference variable to the parent class. It is mainly used when we want to access a variable, method, or constructor in the base class from the derived class.


1 Answers

According to MDN Operator precedence article new without argument list is lower than member access. This suggests that new super.constructor should be evaluated as new (super.constructor) and Firefox and Edge are correct.

Now, according to the specs:

new super.constructor is new NewExpression (https://tc39.github.io/ecma262/#sec-new-operator). NewExpression is in form of MemberExpression, which is in form of SuperProperty which is in form of super.IdentifierName. ES6 standard seems to say the same. So it seems to me that MDN is correct, and so Firefox and Edge are compliant with the spec.

like image 155
Andrew Svietlichnyy Avatar answered Oct 02 '22 22:10

Andrew Svietlichnyy