When is `new Error()` better than `Error()`?

╄→尐↘猪︶ㄣ 提交于 2019-12-06 17:38:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!