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

后端 未结 10 1404
死守一世寂寞
死守一世寂寞 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: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.

提交回复
热议问题