use*_*716 5

如果您无法避免隐藏 global undefined,或者无法避免尝试引用未声明的变量,请使用:

typeof x === 'undefined'
Run Code Online (Sandbox Code Playgroud)

如果您坚持良好的编码实践,并相信让损坏的代码被破坏,请使用:

x === undefined
Run Code Online (Sandbox Code Playgroud)

如果您想要不同的替代方案,您可以使用:

x === void 0;
Run Code Online (Sandbox Code Playgroud)

...wherevoid总是返回undefined,并且不依赖于全局属性。

undefined您可以使用的另一个保护措施是通过在函数中定义适当的方式来以良好的方式使用阴影:

(function( undefined ) {

    // notice that no arguments were passed, 
    // so the `undefined` parameter will be `undefined`

    var x; 

    if( x === undefined ) {

    }

})();
Run Code Online (Sandbox Code Playgroud)

...有些人喜欢给它起一个不同的名称:

(function( undef ) {

    // notice that no arguments were passed, 
    // so the `undefined` parameter will be `undefined`

    var x; 

    if( x === undef ) {

    }

})();
Run Code Online (Sandbox Code Playgroud)