Home  >  Article  >  Web Front-end  >  Introduction to the use of closures and immediate execution functions in js (code example)

Introduction to the use of closures and immediate execution functions in js (code example)

不言
不言forward
2018-10-29 15:09:482461browse

This article brings you an introduction to the use of closures and immediate execution functions in js (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. .

Preface: I have been reading Javascript Advanced Programming in detail recently. For me, the Chinese version of the book has a lot of unsatisfactory translations, so I try to interpret it using what I understand. If there are any mistakes or omissions, we will be very grateful for your pointing them out. Most of the content in this article is quoted from "JavaScript Advanced Programming, Third Edition".

This configuration mechanism of the scope chain leads to a noteworthy side effect, that is, the closure can only obtain the last value of any variable contained in it.

function createArray(){
    var result = new Array();
    for(var i = 0; i < 10; i++) {
        result[i] = function() {
            return i;
        }
    }
    return result;
}

This function will return an array of functions. On the surface, it seems that each function should return its own index value, that is, the function at position 0 returns 0, the function at position 1 returns 1, and so on.

But in fact, each function returns 10, because the active object of createArray is stored in the scope of each function, so they all refer to the same variable i.

When the createArray() function returns, the value of variable i is 10. At this time, each function refers to the same variable i, so the value of i is 10.

// 代码执行过程

createArray();

/*
createArray() {
    var result = new Array();

    var i; // 0,1,2,3,4,5,6,7,8,9,10

    for ( i = 0; i < 10 ; i ++) {
        result[i] = function() {
            return i; 
            // 注意 函数的执行时机,你只有调用函数的时候,才会产生执行环境,沿着作用域链,找到活动对象
            // 这里有个闭包,还记得闭包的概念吗? 有权访问到另外一个函数作用域的变量的函数
        }
    }
    
    /*
    result[0] = function(){
        return i
    }
    result[1] = function(){
        return i
    }
    result[2] = function(){
        return i
    }
    ....
    */
    return result;
}

result = [function(){return i}, function(){return i}....];

*/

createArray()[1](); // 10

So how do we make this function behave as we expect?

You can force the closure to behave as expected by creating another anonymous function, where the immediate execution function is also applied.

//立即执行函数
//我们平时写函数然后调用是这么写的。
//声明函数,调用执行。

function foo(){
    console.log("hi");
}

foo(); // "hi"

//那么,我们可不可以声明调用写一块呢? 这就是申明函数立刻执行。
//好像不可以,控制台报错

function foo(){
    console.log("hi");
}(); //Uncaught SyntaxError: Unexpected token )


//那么如果用括号包裹呢?

(function foo(){
    console.log("hi");
}()); // "hi", 可以了。 这就是立即执行函数!

With the immediate execution function, we can force the closure to behave as we expect.

//改写代码
function createArray() {

    var result = new Array();

    for( var i = 0; i < 10; i ++ ) {
        result[i] = (function(i) { 
            return function(){
                return i;
            }
        }(i));
    }
    return result;
}
createArray()[0](); // 0
createArray()[1](); // 1
createArray()[2](); // 2 
// 这里不只有一种方法,其他方法在此不表。

The above is the detailed content of Introduction to the use of closures and immediate execution functions in js (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete