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.
The super keyword is used to call the constructor of its parent class to access the parent's properties and methods.
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.
The call to super() is required always. Try to write a valid ES6 constructor without super() .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With