Understanding of anonymous functions in Js

Table of contents

        1. N ways to write anonymous functions in js

                Most common usage:

        2. JavaScript anonymous functions and closures

                2.1 Anonymous functions

                        2.1.1 Definition of functions

                        2.1.2 Creation of anonymous functions

                2.2 Closures

                2.3 Example

                2.4 Attention

                        2.4.1 Closures allow inner functions to refer to variables in the parent function, but the variable is the final value

                       

                         2.4.1 Memory leaks

        3. Multiple calling methods of anonymous functions in Javascript

                         Finally, look at the wrong calling method 


 

        1. N ways to write anonymous functions in js

                        Anonymous functions have no actual names and no pointers, which can be understood by understanding the meaning of parentheses. The parentheses have a return value, that is, the return value of the function or expression in the parentheses, so the return value of the function in the parentheses is equal to the return value of the parentheses, it is not difficult to understand (function(){})() can be A function without a name executes the...

                Most common usage:

//代码如下:

(function() { 
alert('water'); 
})(); 

//当然也可以带参数: 
代码如下:

(function(o) { 
alert(o); 
})('water'); 

//想用匿名函数的链式调用?很简单: 
//代码如下:

(function(o) { 
alert(o); 
return arguments.callee; 
})('water')('down'); 

//常见的匿名函数都知道了,看看不常见的: 

//代码如下:

~(function(){ 
alert('water'); 
})();//写法有点酷~ 

//代码如下:

void function(){ 
alert('water'); 
}();//据说效率最高~ 

//代码如下:

+function(){ 
alert('water'); 
}(); 

//代码如下:

-function(){ 
alert('water'); 
}(); 

//代码如下:

~function(){ 
alert('water'); 
}(); 

//代码如下:

!function(){ 
alert('water'); 
}(); 

//代码如下:

(function(){ 
alert('water'); 
}());
//有点强制执行的味道~ 网页打开就会运行并且只能运行一次  

        2. JavaScript anonymous functions and closures

                2.1 Anonymous functions

                        Function is the most flexible object in JavaScript, here is just to explain the purpose of its anonymous function. Anonymous function: It is a function without a function name.

                        2.1.1 Definition of functions

//第一种:这也是最常规的一种
//代码如下:
function double(x){
    return 2 * x;   
}

第二种:这种方法使用了Function构造函数,把参数列表和函数体都作为字符串,很不方便,不建议使用。
//代码如下:
var double = new Function('x', 'return 2 * x;');

//第三种:
var double = function(x) { 
    return 2* x; 
}
//注意“=”右边的函数就是一个匿名函数,创造完毕函数后,又将该函数赋给了变量square。

                        2.1.2 Creation of anonymous functions

//第一种方式:就是上面所讲的定义square函数,这也是最常用的方式之一。

//第二种方式:
//代码如下:
(function(x, y){
    alert(x + y);  
})(2, 3);

//这里创建了一个匿名函数(在第一个括号内),第二个括号用于调用该匿名函数,并传入参数。

                2.2 Closures

                        The English word for closure is closure, which is a very important part of knowledge in JavaScript, because using closure can greatly reduce the amount of our code, make our code look clearer, etc., in short, the function is very powerful. The meaning of closure: 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 JavaScript scope chain).

//示例一
//代码如下:

function checkClosure(){
    var str = 'rain-man';
    setTimeout(
        function(){ alert(str); } //这是一个匿名函数
    , 2000);
}
checkClosure();

                        This example looks very simple. After careful analysis of its execution process, there are still many knowledge points: the execution of the checkClosure function is instantaneous (maybe only 0.00001 milliseconds), and a variable str is created in the checkClosure function body. After the execution, str is not released, 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.

//示例二,优化代码
//代码如下:

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

                2.3 Example

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

//示例三:
//代码如下:

var oEvent = {};
(function(){ 
    var addEvent = function(){ /*代码的实现省略了*/ };
    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 piece of code: oEvent.addEvent(document.getElementById('box') , 'click' , function(){});

//示例四:
//代码如下:

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 calling the anonymous function directly. This little trick is sometimes very useful.

//示例五:
//代码如下:

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 inside a function), so it cannot be accessed from the outside. But here we created the inner function, the inner function can access the variable one; and the global variable outer refers to inner, so calling outer three times will pop up the incremental result.

                2.4 Attention

                        2.4.1 Closures allow inner functions to refer to variables in the parent function, but the variable is the final value

//示例六:
//代码如下:

/**
 * <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 each <li&rt; element, 4 always pops up, not the element subscript we expected. Why is this? It has already been mentioned in the precautions (final value). Obviously, this explanation is too simple. When the mouseover event calls the listening function, it first checks whether i is defined inside the anonymous function (function(){alert(i);}), and the result is that it is not defined; so it will look up and find The result is already defined, and the value of i is 4 (the value of i after the loop); therefore, 4 is finally popped up every time.

//解决方法一:
//代码如下:

var lists = document.getElementsByTagName('li');
for(var i = 0 , len = lists.length ; i < len ; i++){
    (function(index){
        lists[ index ].onmouseover = function(){
            alert(index);    
        };                    
    })(i);
}


//解决方法二:
//代码如下:

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


//解决方法三:
//代码如下:

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

                       

                         2.4.1 Memory leaks

                                Using closures is very easy to cause browser memory leaks, and in severe cases, the browser will hang

        3. Multiple calling methods of anonymous functions in Javascript

There are many ways to define functions in Javascript, and function literals are one of them. Such as var fun = function(){}, if function is not assigned to fun, then it is an anonymous function. Ok, let's see how the anonymous function is called.

//方式1,调用函数,得到返回值。强制运算符使函数调用执行
//代码如下:

(function(x,y){ 
    alert(x+y); 
    return x+y; 
}(3,4)); 
//方式2,调用函数,得到返回值。强制函数直接量执行再返回一个引用,引用再去调用执行
//代码如下:

(function(x,y){ 
    alert(x+y); 
    return x+y; 
})(3,4); 


这种方式也是很多库爱用的调用方式,如jQuery,Mootools
//方式3,使用void
//代码如下:


void function(x) { 
      x = x-1; 
      alert(x); 
}(9);
//方式4,使用-/+运算符
//代码如下:

-function(x,y){ 
    alert(x+y); 
    return x+y; 
}(3,4); 

+function(x,y){ 
    alert(x+y); 
    return x+y; 
}(3,4); 

--function(x,y){ 
    alert(x+y); 
    return x+y; 
}(3,4); 

++function(x,y){ 
    alert(x+y); 
    return x+y; 
}(3,4);
//方式5,使用波浪符(~)
//代码如下:


~function(x, y) { 
    alert(x+y); 
   return x+y; 
}(3, 4);

                         Finally, look at the wrong calling method 

//代码如下:

function(x,y){ 
    alert(x+y); 
    return x+y; 
}(3,4);

Guess you like

Origin blog.csdn.net/Jsy_997/article/details/124474285