js闭包例子

阅读更多

//1级作用域(window)

function test(){//2级作用域(test)

var count = 1;

        //函数test()内部最终返回函数add()

return function add(){//3级作用域(add)

        //add()函数内部引用外部函数test()的变量i

count = count * 2;

return count;

}

}

 

//调用test()方法,该方法返回函数add()

var add = test();

 

//调用函数打印5次

for(i = 0;i <= 5;i++){

console.log(add());

}

输出结果:

2

4

8

16

32

64

你可能感兴趣的:(js闭包例子)