The simplest and perhaps the worst way of declaring a global within a function is to declare it informally within the function:
Code:
function dosomething(){
dosomethingrun = true;
}
dosomething();
alert(dosomethingrun); //alerts 'true', unless this is IE and there's an element in the parsed DOM
// with a name or id of 'dosomethingrun', then it will alert 'object' and be a reference to that element
That's bad enough, but this is also a possible scenario:
Code:
function dosomething(){
dosomethingrun = true;
}
alert(dosomethingrun); // throws an error and stops script processing in some, perhaps all browsers
Any informally declared global has a chance of conflicting with another global of the same name and/or the DOM in IE which creates its own globals via the implied document.all collection.
The first conflict can be avoided by careful coding, use a unique name for each global.
The second can be avoided by formally declaring the variable in the global scope, ex:
Code:
var dosomethingrun;
function dosomething(){
dosomethingrun = true;
}
alert(dosomethingrun); //alerts 'undefined'
dosomething();
alert(dosomethingrun); //alerts 'true'
There's a better way. Since you want to declare this global inside a function and have it be available outside the function, you may make it a property of the function, ex:
Code:
function dosomething(){
dosomething.run = true;
}
alert(dosomething.run); //alerts 'undefined'
dosomething();
alert(dosomething.run); //alerts 'true'
It's no longer truly a global, yet is available in the global scope. And it cannot conflict with the DOM.
Bookmarks