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

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

    if (typeof someVar === "undefined") {
        var someVar = "hi!";
    }
    

    will check if someVar (local or global) is undefined.

    If you want to check for a global variable you can use

    if(window['someVar'] === undefined) {
        ...
    }
    

    assuming this is in a browser :)

提交回复
热议问题