问题
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