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

白昼怎懂夜的黑 提交于 2019-11-28 18:29:39

问题


JSLint is not passing this as a valid code:

/* global someVar: false */
if (typeof someVar === "undefined") {
    var someVar = "hi!";
}

What is the correct way?


回答1:


/*global window */

if (window.someVar === undefined) {
    window.someVar = 123456;
}

if (!window.hasOwnProperty('someVar')) {
    window.someVar = 123456;
}



回答2:


/**
 * @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.




回答3:


If you are wanting to assign a global variable only if it doesn't already exist, try:

window.someVar = window.someVar || 'hi';

or

window['someVar'] = window['someVar'] || 'hi';



回答4:


try

variableName in window

or

typeof window[variableName] != 'undefined'

or

window[variableName] !== undefined

or

window.hasOwnProperty(variableName)



回答5:


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.




回答6:


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 :)




回答7:


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".



回答8:


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){

}


来源:https://stackoverflow.com/questions/11596315/what-is-the-correct-way-to-check-if-a-global-variable-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!