GOTO 0
GOTO 0

Reputation: 47801

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.

Upvotes: 7

Views: 156

Answers (1)

Andrew Svietlichnyy
Andrew Svietlichnyy

Reputation: 761

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.es/ecma262/multipage/ecmascript-language-expressions.html#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.

Upvotes: 3

Related Questions