What is the correct way to check if a global variable exists?

后端 未结 10 1360
死守一世寂寞
死守一世寂寞 2020-12-13 06:02

JSLint is not passing this as a valid code:

/* global someVar: false */
if (typeof someVar === \"undefined\") {
    var someVar = \"hi!\";
}
<
相关标签:
10条回答
  • 2020-12-13 06:18
    /*global window */
    
    if (window.someVar === undefined) {
        window.someVar = 123456;
    }
    
    if (!window.hasOwnProperty('someVar')) {
        window.someVar = 123456;
    }
    
    0 讨论(0)
  • 2020-12-13 06:20

    bfavaretto is incorrect.

    Setting the global undefined to a value will not alter tests of objects against undefined. Try this in your favorite browsers JavaScript console:

    var udef; var idef = 42;
    alert(udef === undefined); // Alerts "true".
    alert(idef === undefined); // Alerts "false".
    window.undefined = 'defined';
    alert(udef === undefined); // Alerts "true".
    alert(idef === undefined); // Alerts "false".
    

    This is simply due to JavaScript ignoring all and any values attempted to be set on the undefined variable.

    window.undefined = 'defined';
    alert(window.undefined); // Alerts "undefined".
    
    0 讨论(0)
  • 2020-12-13 06:25
    /**
     * @param {string} nameOfVariable
     */
    function globalExists(nameOfVariable) {
        return nameOfVariable in window
    }
    

    It doesn't matter whether you created a global variable with var foo or window.foo — variables created with var in global context are written into window.

    0 讨论(0)
  • 2020-12-13 06:27

    This would be a simple way to perform the check .

    But this check would fail if variableName is declared and is assigned with the boolean value: false

    if(window.variableName){
    
    }
    
    0 讨论(0)
提交回复
热议问题