问题
The ES5 language spec clearly states that Error(foo)
does the same thing as new Error(foo)
.
But I notice that in the wild, the longer new Error(foo)
form is much more common.
Is there some reason for this?
Is there any situation where using new Error(foo)
is preferable to using Error(foo)
?
回答1:
Is there some reason for this?
It's simply the habit of always calling constructors with new
. Consistency rules!
It's a good practice to do even when they work without new
, and recommended by several style guides and related tooling. Btw, since ES6 Error is subclassible, and its subclasses will require new
.
来源:https://stackoverflow.com/questions/38759428/when-is-new-error-better-than-error