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

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

    I think this is actually a problem with JSLint. It will issue the following error:

    Unexpected 'typeof'. Compare directly with 'undefined'.

    I believe this is bad advice. In JavaScript, undefined is a global variable that is, usually, undefined. But some browsers allow scripts to modify it, like this: window.undefined = 'defined'. If this is the case, comparing directly with undefined can lead to unexpected results. Fortunately, current ECMA 5 compliant browsers do not allow assignments to undefined (and will throw an exception in strict mode).

    I prefer typeof someVar === "undefined", as you posted, or someVar in window as Susei suggested.

提交回复
热议问题