Home >Web Front-end >JS Tutorial >Detailed discussion on the use of JavaScript function closures and precautions code detailed explanation
The English word for closure is closure, which is a very important part of knowledge in JavaScript, because using closures can greatly reduce the amount of our code, make our code look clearer, etc. In short, it is very functional. powerful.
The meaning of closure: To put it bluntly, closure is the nesting of functions. The inner function can use all the variables of the outer function, even if the outer function has been executed (this involves the function of JavaScript domain chain).
Example 1
function checkClosure(){ var str = 'rain-man'; setTimeout( function(){ alert(str); } //这是一个匿名函数 , 2000); } checkClosure();
This example looks very simple. There are still many knowledge points after careful analysis of its execution process: the execution of the checkClosure function is instantaneous (maybe it only takes 0.00001 milliseconds) ), a variable str is created in the function body of checkClosure. After checkClosure is executed, str is not released. This is because the anonymous function in setTimeout has a reference to str. After 2 seconds, the anonymous function in the function body is executed, and str is released.
Example 2, optimize code
function forTimeout(x, y){ alert(x + y); } function delay(x , y , time){ setTimeout('forTimeout(' + x + ',' + y + ')' , time); } /** * 上面的delay函数十分难以阅读,也不容易编写,但如果使用闭包就可以让代码更加清晰 * function delay(x , y , time){ * setTimeout( * function(){ * forTimeout(x , y) * } * , time); * } */
The biggest use of anonymous functions is to create closures (this is one of the features of the JavaScript language), and you can also build namespaces to reduce the number of global variables use.
Example 3:
var oEvent = {}; (function(){ var addEvent = function(){ /*代码的实现省略了*/ }; function removeEvent(){} oEvent.addEvent = addEvent; oEvent.removeEvent = removeEvent; })();
Example 4:
var rainman = (function(x , y){ return x + y; })(2 , 3); /** * 也可以写成下面的形式,因为第一个括号只是帮助我们阅读,但是不推荐使用下面这种书写格式。 * var rainman = function(x , y){ * return x + y; * }(2 , 3); */
Here we create a variable rainman and initialize it to 5 by directly calling the anonymous function. This little trick is sometimes Very practical.
Example 5:
var outer = null; (function(){ var one = 1; function inner (){ one += 1; alert(one); } outer = inner; })(); outer(); //2 outer(); //3 outer(); //4
The variable one in this code is a local variable (because it is defined within a function), so it is not accessible from the outside. But here we created the inner function, which can access the variable one; and the global variable outer refers to inner, so calling outer three times will pop up the incremental result.
Note: Closure allows the inner function to refer to the variable in the parent function, but the variable is the final value
Example 6:
/** * <body> * <ul> * <li>one</li> * <li>two</li> * <li>three</li> * <li>one</li> * </ul> */ var lists = document.getElementsByTagName('li'); for(var i = 0 , len = lists.length ; i < len ; i++){ lists[ i ].onmouseover = function(){ alert(i); }; }
You will find that when the mouse moves over For each
Solution one:
var lists = document.getElementsByTagName('li'); for(var i = 0 , len = lists.length ; i < len ; i++){ (function(index){ lists[ index ].onmouseover = function(){ alert(index); }; })(i); }
Solution two:
var lists = document.getElementsByTagName('li'); for(var i = 0, len = lists.length; i < len; i++){ lists[ i ].$$index = i; //通过在Dom元素上绑定$$index属性记录下标 lists[ i ].onmouseover = function(){ alert(this.$$index); }; }
Solution three:
function eventListener(list, index){ list.onmouseover = function(){ alert(index); }; } var lists = document.getElementsByTagName('li'); for(var i = 0 , len = lists.length ; i < len ; i++){ eventListener(lists[ i ] , i); }
The above is the detailed content of Detailed discussion on the use of JavaScript function closures and precautions code detailed explanation. For more information, please follow other related articles on the PHP Chinese website!