Home > Web Front-end > JS Tutorial > A detailed discussion of JavaScript anonymous functions and closures_javascript skills

A detailed discussion of JavaScript anonymous functions and closures_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-05-16 16:31:26
Original
1374 people have browsed it

1. Anonymous function
Functions are the most flexible objects in JavaScript. Here we only explain the use of anonymous functions. Anonymous function: It is a function without a function name.

1.1 Definition of function, first briefly introduce the definition of function, which can be roughly divided into three ways

The first type: This is also the most common type

Copy code The code is as follows:

function double(x){
Return 2 * x;
}

Second method: This method uses the Function constructor and treats both the parameter list and the function body as strings. This is very inconvenient and is not recommended.

Copy code The code is as follows:

var double = new Function('x', 'return 2 * x;');

Third type:

var double = function(x) { return 2* x; }
Note that the function on the right side of "=" is an anonymous function. After creating the function, the function is assigned to the variable square.

1.2 Creation of anonymous functions

The first method is to define the square function as mentioned above, which is also one of the most commonly used methods.

The second way:

Copy code The code is as follows:

(function(x, y){
alert(x y);
})(2, 3);

An anonymous function is created here (inside the first bracket), and the second bracket is used to call the anonymous function and pass in the parameters.

2. Closure
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 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 JavaScript scope chain).

Example 1

Copy code The code is as follows:

function checkClosure(){
var str = 'rain-man';
setTimeout(
           function(){ alert(str); } //This is an anonymous function
, 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), and a variable str is created in the function body of checkClosure. , str is not released after checkClosure is executed, 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, optimized code

Copy code The code is as follows:

function forTimeout(x, y){
alert(x y);
}
function delay(x, y, time){
setTimeout('forTimeout(' x ',' y ')' , time);
}
/**
* The above delay function is very difficult to read and not easy to write, but if you use closures, the code can be made clearer
* function delay(x, y, time){
* setTimeout(
* function(){
* forTimeout(x, y)
*                                                                                         * , time);
* }
​*/

3. Example

The biggest use of anonymous functions is to create closures (which is one of the features of the JavaScript language), and they can also build namespaces to reduce the use of global variables.

Example 3:

Copy code The code is as follows:

var oEvent = {};
(function(){
var addEvent = function(){ /*Code implementation omitted*/ };
Function removeEvent(){}

oEvent.addEvent = addEvent;
oEvent.removeEvent = removeEvent;
})();

In this code, the functions addEvent and removeEvent are local variables, but we can use it through the global variable oEvent, which greatly reduces the use of global variables and enhances the security of the web page. We want to use this code: oEvent.addEvent(document.getElementById('box') , 'click' , function(){});

Example 4:

Copy code The code is as follows:

var rainman = (function(x , y){
Return x y;
})(2, 3);
/**
* can also be written in the following form, because the first bracket only helps us read, but the following writing format is not recommended.
* 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:

Copy code The code is as follows:

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.

4. Attention
4.1 Closure allows the inner function to refer to the variable in the parent function, but the variable is the final value

Example 6:

Copy code The code is as follows:

/**
 *
 *

     *    
  • one

  •  *    
  • two

  •  *    
  • three

  •  *    
  • one

  •  *

 */

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 each

Solution 1:

Copy code The code is as follows:

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 2:

Copy code The code is as follows:

var lists = document.getElementsByTagName('li');
for(var i = 0, len = lists.length; i < len; i ){
Lists[ i ].$$index = i; //Record the subscript by binding the $$index attribute on the Dom element
Lists[ i ].onmouseover = function(){
alert(this.$$index);
};
}

Solution three:

Copy code The code is as follows:

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);
}

4.2 Memory leak

Using closures can easily cause memory leaks in the browser. In serious cases, the browser will hang. If you are interested, you can refer to: http://www.jb51.net/article/57404.htm

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template