最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - When is `new Error()` better than `Error()`? - Stack Overflow

programmeradmin5浏览0评论

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)?

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)?

Share Improve this question asked Aug 4, 2016 at 5:53 joeytwiddlejoeytwiddle 31.3k14 gold badges127 silver badges114 bronze badges 2
  • 3 There could be static code checks considering uppercase function names classes and checking that they must be called with new. – Ingo Bürk Commented Aug 4, 2016 at 6:11
  • 1 Another reason is people not knowing or knowing but preferring it because that's what they're used to given that using new has been the standard pattern. – Ingo Bürk Commented Aug 4, 2016 at 6:14
Add a comment  | 

1 Answer 1

Reset to default 26

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.

发布评论

评论列表(0)

  1. 暂无评论