Is JavaScript's “new” keyword considered harmful?

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

    I have just read some parts of his Crockfords book "Javascript: The Good Parts". I get the feeling that he considers everything that ever has bitten him as harmful:

    About switch fall through:

    I never allow switch cases to fall through to the next case. I once found a bug in my code caused by an unintended fall through immediately after having made a vigorous speech about why fall through was sometimes useful. (page 97, ISBN 978-0-596-51774-8)

    About ++ and --

    The ++ (increment) and -- (decrement) operators have been known to contribute to bad code by encouraging exessive trickiness. They are second only to faulty architecture in enabling viruses and other security menaces. (page 122)

    About new:

    If you forget to include the new prefix when calling a constructor function, then this will not be bound to the new object. Sadly, this will be bound to the global object, so instead of augmenting your new object, you will be clobbering global variables. That is really bad. There is no compile warning, and there is no runtime warning. (page 49)

    There are more, but I hope you get the picture.

    My answer to your question: No, it's not harmful. but if you forget to use it when you should you could have some problems. If you are developing in a good environment you notice that.

    Update

    About a year after this answer was written the 5th edition of ECMAScript was released, with support for strict mode. In strict mode, this is no longer bound to the global object but to undefined.

提交回复
热议问题