Is JavaScript's “new” keyword considered harmful?

前端 未结 12 2097
情书的邮戳
情书的邮戳 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:36

    The rationale behind not using the new keyword, is simple:

    By not using it at all, you avoid the pitfall that comes with accidentally omitting it. The construction pattern that YUI uses, is an example of how you can avoid the new keyword altogether"

    var foo = function () {
        var pub= { };
        return pub;
    }
    var bar = foo();
    

    Alternatively you could so this:

    function foo() { }
    var bar = new foo();
    

    But by doing so you run risk of someone forgetting to use the new keyword, and the this operator being all fubar. AFAIK there is no advantage to doing this (other than you are used to it).

    At The End Of The Day: It's about being defensive. Can you use the new statement? Yes. Does it make your code more dangerous? Yes.

    If you have ever written C++, it's akin to setting pointers to NULL after you delete them.

提交回复
热议问题