Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new.target with a prefix operator

"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

like image 678
Michael Jasper Avatar asked Nov 08 '22 18:11

Michael Jasper


1 Answers

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!')
}
like image 84
Michael Jasper Avatar answered Nov 15 '22 12:11

Michael Jasper