"The new.target property lets you detect whether a function or constructor was called using the new operator" [1]
I can use new.target
in an if statement to throw an error if a function was not called using new
:
if(!new.target){
throw new Error('Must be called with new keyword!')
}
However, safari prevents new.target
from being used with the !
in this way, with the error message
new.target can't come after a prefix operator
I tracked this down to this line in Webkit.
However the positive condition can be checked!
if(new.target){}
else{
throw new Error('Must be called with new keyword!')
}
Is this an error with safari's parsing engine? Or alternatively, should I be using new.target
in the way they enforce?
simple repro: https://codepen.io/mdjasper/pen/eEWORY?editors=0012
Edit: This issue has been filed on webkit bugzilla: https://bugs.webkit.org/show_bug.cgi?id=157970
This syntax should be supported, and the error was confirmed to be a webkit bug:
if(!new.target){
throw new Error('Must be called with new keyword!')
}
A patch has been written and merged, and will ship with a future version of webkit
https://bugs.webkit.org/show_bug.cgi?id=157970#c17
Until the fix lands in a released version, a workaround is to explicitly check new.target
if(new.target === undefined){
throw new Error('Must be called with new keyword!')
}
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