How dangerous is it in JavaScript, really, to assume undefined is not overwritten?

后端 未结 8 958
Happy的楠姐
Happy的楠姐 2020-11-27 04:36

Every time anyone mentions testing against undefined, it\'s pointed out that undefined is not a keyword so it could be set to \"hello\", so you sho

8条回答
  •  情深已故
    2020-11-27 04:42

    Only you know what code you use, and therefore how dangerous it is. This question can't be answered in the way you've clarified you want it answered.

    1) Create a team policy, disallow redefining undefined, reserving it for its more popular usage. Scan your existing code for undefined left assignment.

    2) If you don't control all the scenarios, if your code is used outside situations you or your policies control, then obviously your answer is different. Scan the code that does use your scripts. Heck, scan web for statistics of undefined left assignment if you wish, but I doubt that's been done for you, because it's easier to just pursue answer #1 or #3 here instead.

    3) And if that answer isn't good enough, it's probably because, again, you require a different answer. Maybe you are writing a popular library that will be used inside corporate firewalls, and you don't have access to the calling code. Then use one of the other fine answers here. Note the popular jQuery library practices sound encapsulation, and begins:

    (function( window, undefined ) {
    

    Only you can answer your question in the specific way you seek. What more is there to say?

    edit: p.s. if you really want my opinion, I'll tell you it's not dangerous at all. Anything that would be so likely to cause defects (such as assigning to undefined, which is obviously a well-documented risky behaviour) is itself a defect. It's the defect that is the risk. But that's just in my scenarios, where I can afford to hold that perspective. As I'd recommend you do, I answered the question for my use-cases.

提交回复
热议问题