Is JavaScript's “new” keyword considered harmful?

前端 未结 12 2076
情书的邮戳
情书的邮戳 2020-11-21 23:18

In another question, a user pointed out that the new keyword was dangerous to use and proposed a solution to object creation that did not use new.

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 23:44

    Here is the briefest summary I could make of the two strongest arguments for and against using the new operator:

    Argument against new

    1. Functions designed to be instantiated as objects using the new operator can have disastrous effects if they are incorrectly invoked as normal functions. A function's code in such a case will be executed in the scope where the function is called, instead of in the scope of a local object as intended. This can cause global variables and properties to get overwritten with disastrous consequences.
    2. Finally, writing function Func(), and then calling Func.prototype and adding stuff to it so that you can call new Func() to construct your object seems ugly to some programmers, who would rather use another style of object inheritance for architectural and stylistic reasons.

    For more on this argument check out Douglas Crockford's great and concise book Javascript: The Good Parts. In fact check it out anyway.

    Argument in favor of new

    1. Using the new operator along with prototypal assignment is fast.
    2. That stuff about accidentally running a constructor function's code in the global namespace can easily be prevented if you always include a bit of code in your constructor functions to check to see if they are being called correctly, and, in the cases where they aren't, handling the call appropriately as desired.

    See John Resig's post for a simple explanation of this technique, and for a generally deeper explanation of the inheritance model he advocates.

提交回复
热议问题