1 What is a global variable
, The global object is straightforward to use global variables are declared outside of any function or have not declared additional property called window, this window (usually) points to the global object itself, the excessive use of global variables will result in code readability reduce, global variables larger share of memory
2 to solve the implicit global variables
Why will not consciously create a global variable, first of all, you can not even need to declare variable can be used; second, JavaScript has implicit global concept, which means you do not declare any variables that will become a global object properties, the following two examples of good indication, must use var variable declaration
SUM function (X, Y) { // write global variable implicitly Result Result = X + Y; return Result; } // correct wording function SUM (X, Y) { var Result = X + Y; return Result; }
// so that when you call this function, write will give birth to a global variable b
function foo() {
var a = b = 0;
// ...
}
// correct wording
foo function () {
var A, B;
// ... A = B = 0; // are two local variables
}
2 difference implicit global variables with the var function created
// definition of three global variables var global_var = . 1 ; global_novar = 2 ; // a negative, not a (function () { global_fromfunc = . 3 ; // negative example. Wrong } ()); // try to delete the Delete global_var; // false the Delete global_novar; // to true the Delete global_fromfunc; // to true // Implicit global variables are not really global variables, but they are properties of the global object. Properties can be deleted by the delete operator, and the variable is impossible: