Latest Analysis of JS Global and Local Variables

  • 2021-06-29 10:15:45
  • OfStack

It's this blind, irrational research test that confuses me. Is it necessary to do so ?In fact, it is not necessary to do so many 1 tests after understanding the principle, and then get the rules, ECMAScript rules have been defined.

var's rule is to declare that a variable is an internal variable using var, or to call a global variable first, no matter how many layers of functions it has.

The rule of this is that the this in the method function always points to itself, and the this in the normal function always points to DOMWindow.


// GodDamnTest1
function Foo() { 
var a = 123; //  local variable ,  Global variables for all subfunctions 
this.a = 456; //  Object Properties 
(function() { 
alert(a); // 123,  Overall situation 
alert(this.a); // undefined,  General function , this point DOMWindow 
})(); 
} 
var f = new Foo(); 
// GodDamnTest2
function Foo() { 
var a = 123; 
this.a = 456; 
(function(a) { //  Local declaration 
alert(a); // 456,  Locally declared by a function a Overlay the whole world  
})(this.a); 
} 
var f = new Foo(); 
// GodDamnTest3
function Foo() { 
var a = 123; 
this.a = 456; 
(function() { 
alert(a); // 123,  Overall situation 
alert(this.a); // undefined, DOMWindow 
this.b = 789; // window.b = 789
})(); 
(function() { 
alert(this.b); // 789, window.b
})(); 
} 
var f = new Foo(); 
(function() { 
alert(this.b); // 789, window.b
})(); 

// GodDamnTest4
function Foo() { 
(function() { 
this.b = 789; // window.b = 789
})(); 
(function() { 
alert(this.b); // 789, window.b
var b = 0; 
alert(b); // 0,  This test is also written out !
})(); 
} 
var f = new Foo(); 
(function() { 
alert(this.b); // 789, window.b
alert(b); // 789, window.b
})(); 

Surprisingly, for the last alert (b), the result is still 789. //no damn surprise at all!


// GodDamnTest5
function Foo() { 
(function() { 
this.b = 789; // window.b = 789
})(); 
(function() { 
alert(this.b); // 789, window.b
alert(b); // undefined,  Overall situation 
var b = 0; 
alert(b); // 0,  There are also such tests !
})(); 
} 
var f = new Foo(); 
(function() { 
alert(this.b); // 789, window.b
alert(b); // 789, window.b
})();

PS:JS Method for Deleting Local Variables


alert('value:'+str+'\ttype:'+typeof(str)) // Before declaring a variable, reference 
var str="dd";
alert('value:'+str+'\ttype:'+typeof(str)) // After declaring and assigning variables, reference 
str=undefined; *  // Delete local variables 
alert('value:'+str+'\ttype:'+typeof(str)) // After removing variables, reference, and 1 Same 

Related articles: