Are there problems with calling JavaScript constructors as functions(without new?)

后端 未结 2 1040
醉梦人生
醉梦人生 2021-02-07 20:37

Recently, I have got into a habit of calling things like RegExp, String, Number, Object, TypeError, etc without \"new\".

e.g:

throw (TypeError(\"Error\")         


        
2条回答
  •  既然无缘
    2021-02-07 21:30

    As documented in another answer, some built in constructors are written to be able to be called as functions. So as long as you aren't polluting your global namespace, I believe you should be fine with the example you listed.

    That being said, in most cases, I wouldn't get used to this habit; the new operator adds to code clarity, which is more important than brevity. The ability to use native constructors without the new operator is also inconsistently applied across constructors.

提交回复
热议问题