Home >Web Front-end >JS Tutorial >Parse JS global variables and local variables
It’s this kind of blind research and testing without any principle that makes me confused. Is it necessary to do this? In fact, if you understand the principle, there is no need to conduct so many tests one by one, and then draw the rules. ECMAScript rules have been defined.
The rules for var are: Using var to declare variables is internal variables, otherwise global variables are called first, no matter how many layers of functions.
The rules for this are: This in the method function always points to itself, and this in the ordinary function always points to the DOMWindow.
// GodDamnTest1 function Foo() { var a = 123; // 局部变量, 所有子函数的全局变量 this.a = 456; // 对象属性 (function() { alert(a); // 123, 全局 alert(this.a); // undefined, 普通函数, this指向DOMWindow })(); } var f = new Foo(); // GodDamnTest2 function Foo() { var a = 123; this.a = 456; (function(a) { // 局部声明 alert(a); // 456, 被函数局部声明的a覆盖了全局 })(this.a); } var f = new Foo(); // GodDamnTest3 function Foo() { var a = 123; this.a = 456; (function() { alert(a); // 123, 全局 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, 这样的测试也写出来了! })(); } var f = new Foo(); (function() { alert(this.b); // 789, window.b alert(b); // 789, window.b })();
Surprisingly, the result of the last alert(b) 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, 全局 var b = 0; alert(b); // 0, 还有这种测试! })(); } var f = new Foo(); (function() { alert(this.b); // 789, window.b alert(b); // 789, window.b })();
PS: How to delete local variables in JS
alert('value:'+str+'\ttype:'+typeof(str)) //声明变量前,引用 var str="dd"; alert('value:'+str+'\ttype:'+typeof(str)) //声明并赋值变量后,引用 str=undefined; //删除局部变量 alert('value:'+str+'\ttype:'+typeof(str)) //取消变量后,引用,和第一个相同
The above is the detailed content of Parse JS global variables and local variables. For more information, please follow other related articles on the PHP Chinese website!