JS-闭包练习

首先,第一个输出,因为前置运算,i要先参与输出,然后再自增,所以输出为0

第二个输出,因为f1和f2是不同的函数,不共享i变量,所以输出也为0

第三个输出,因为是f1,共享i,所以i加了1,输出为1

let foo = function(){
    let i = 0;
    return function(){
        console.log(i++);
    }
}
let f1 = foo();
let f2 = foo();
f1();// 0
f2();// 0
f1();// 1

首先,从函数和下面的闭包可以看出,第一行和第二行代码是迷惑人的,正常思考,输出就是。

let x = 100;
let y = 200;
let funA = function(x){
    x += 1;
    let y = 201;
    let funB = function(){
        console.log(x); // 102
        console.log(y); // 201
    }
    return funB;
}
let f = funA(101);
f();

猜你喜欢

转载自www.cnblogs.com/CccK-html/p/11488204.html