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

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

提交回复
热议问题