It is this blind and unprincipled research and testing that made me faint. Is it necessary to do this? In fact, there is no need to do so many tests after understanding the principles, and then draw the rules. The ECMAScript rules have been defined.
The rule of var is: Use var to declare a variable that is an internal variable, otherwise it is to call the global variable first, no matter how many layers of functions are.
The rule of this is: this in the method function always points to itself, and this in the ordinary function always points to DOMWindow.
// GodDamnTest1function Foo() { var a = 123; // Local variable, global variables of all subfunctions this.a = 456; // Object property(function() { alert(a); // 123, global alert(this.a); // undefined, normal function, this point to DOMWindow })(); } var f = new Foo(); // GodDamnTest2function Foo() { var a = 123; this.a = 456; (function(a) { // Local declaration alert(a); // 456, The global is overridden by a locally declared by the function})(this.a); } var f = new Foo(); // GodDamnTest3function Foo() { var a = 123; this.a = 456; (function() { alert(a); // 123, global 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})(); // GodDamnTest4function Foo() { (function() { this.b = 789; // window.b = 789})(); (function() { alert(this.b); // 789, window.bvar b = 0; alert(b); // 0, such a test has been written!})(); } var f = new Foo(); (function() { alert(this.b); // 789, window.balert(b); // 789, window.b})();Surprisingly, the last alert(b) still resulted in 789. // no damn surprise at all!
// GodDamnTest5function Foo() { (function() { this.b = 789; // window.b = 789})(); (function() { alert(this.b); // 789, window.balert(b); // undefined, global var b = 0; alert(b); // 0, there is also such test!})(); } var f = new Foo(); (function() { alert(this.b); // 789, window.balert(b); // 789, window.b})();PS: JS method to delete local variables
alert('value:'+str+'/ttype:'+typeof(str)) //Before declaring the variable, refer to var str="dd";alert('value:'+str+'/ttype:'+typeof(str)) //After declaring and assigning the variable, refer to str=undefined; //Delete the local variable alert('value:'+str+'/ttype:'+typeof(str)) //After canceling the variable, refer to str=undefined, same as the first oneThe above is the latest analysis of JS global variables and local variables introduced to you by the editor. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!