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

后端 未结 8 972
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:44

    No proper code will do such a thing. But you can never know what some wannabe-smart developer or a plugin/library/script you are using did. On the other side, it's extremely unlikely and modern browsers will not allow overwriting undefined at all, so if you are using such a browser for development you'll quickly notice if any code tries to overwrite it.


    And even though you did not ask for it - many people will probably find this question when looking for the more common "how to protect against redefined undefined" issue, so I'll answer that anyway:

    There's a very good way to get a truly undefined undefined no matter how old the browser is:

    (function(undefined) {
        // your code where undefined is undefined
    })();
    

    This works because an argument that is not specified is always undefined. You can also do it with a function that accepts some real arguments, e.g. like this when you are using jQuery. It's usually a good idea to ensure a sane environment in this way:

    (function($, window, undefined) {
        // your code where undefined is undefined
    })(jQuery, this);
    

    Then you can be sure that inside that anonymous function the following things are true:

    • $ === jQuery
    • window === [the global object]
    • undefined === [undefined].

    However, note that sometimes typeof x === 'undefined' is actually necessary: If the variable x has never been set to a value (contrary to being set to undefined), reading x in a different way such as if(x === undefined) will throw an error. This does not apply to object properties though, so if you know that y is always an object, if(y.x === undefined) is perfectly safe.

提交回复
热议问题