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

后端 未结 8 963
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:45

    No, I never have. This is mostly because I develop on modern browsers, which are mostly ECMAScript 5 compliant. The ES5 standard dictates that undefined is now readonly. If you use strict mode (you should), an error will be thrown if you accidentally try to modify it.

    undefined = 5;
    alert(undefined); // still undefined
    
    'use strict';
    undefined = 5; // throws TypeError
    

    What you should not do is create your own scoped, mutable undefined:

    (function (undefined) {
        // don't do this, because now `undefined` can be changed
        undefined = 5;
    })();
    

    Constant is fine. Still unnecessary, but fine.

    (function () {
        const undefined = void 0;
    })();
    

提交回复
热议问题