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

后端 未结 2 1039
醉梦人生
醉梦人生 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:29

    Be aware the result can be different.

    For example, the Number constructor creates Number objects, but when called as a function it only does type coercion to primitive Number.

    new Number(123); // Number { 123 }
    Number(123); // 123
    

    But yes, there are lots of the cases in which it doesn't matter whether you use new or not. They exist because of backwards compatibility, but with recently introduced constructors like Set or Map do require new.

    In general, I would recommend using new when you want to create a new object. Then,

    • If you only want to do type coercion, you must call Boolean, Number or String without new.
    • For the same reason, if you want coerce to Object type, I wouldn't use new, but it doesn't matter.
    • If you want to create a primitive which doesn't have literal syntax, you must call Symbol without new.
    • If you want to create an object wrapper of a primitive value, you must call Boolean, Number, String or Symbol with new.
    • If you want to instantiate an old constructor like Array, Object, RegExp, Error, etc., I would use new, but it doesn't matter.
    • If you want to instantiate a recently introduced constructor like Set, Map, WeakSet, WeakMap, typed arrays, etc., you must call it with new.

    For the old constructors that it doesn't matter, it's like they call themselves with new if you omit it. For example, for RegExp,

    When RegExp is called as a function rather than as a constructor, it creates and initializes a new RegExp object. Thus the function call RegExp(…) is equivalent to the object creation expression new RegExp(…) with the same arguments.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题