闭包

从技术上来讲,在JS中,每个function都是闭包,因为它总是能访问在它外部定义的数据。

当你return 内部function时,内部function会‘close-over’外部function的变量直到内部function结束。\

An inner function can never access these variables directly from an
outer function. 

If you want access to a containing
scope’s arguments object, you’ll need to save a reference into another variable
that the closure can access.

所以闭包了的函数没有办法直接拿到外部function的执行结果。

 

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

2.function createFucntion(){

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

 

1,i 是直接拿到了createFucntion()的 activation object里面的的最终执行结果。

2,把当前的i值,作为参数num,传递给一个无法获取“createFucntion()'s activation object”里面的值的匿名函数。

然后为数组赋值。

或者可以用 var num = i , 不传递参数,然后直接在内部函数用 i  (内部函数可以直接拿到外部函数中的变量的值)

 

posted @ 2017-04-21 10:28  Esther_Cheung  阅读(129)  评论(0编辑  收藏  举报