当前位置: 代码迷 >> JavaScript >> 浅谈javascript闭包1-英语水平不行,自各儿理解翻译
  详细解决方案

浅谈javascript闭包1-英语水平不行,自各儿理解翻译

热度:263   发布时间:2012-11-01 11:11:31.0
浅谈javascript闭包1--英语水平不行,自己理解翻译

?

??首先说明下,本人学习的javascript师承--大漠。是我们群一个非常牛b的任务。

一下文章系列是从一个外文网站上面看到的,所以加上自己的理解就发出来,大家共同学习

下面是一个普通的javascript函数

function?sayHello(name)?{
??var?text?= 'Hello?'?+ name;//定义个临时string对象text
??var?sayAlert?= function()?{ alert(text); }//定义临时function对象sayAlert
??sayAlert();//执行
}
sayHello("Bob");//Bob

?一个简单的闭包实例

闭包其实可以用2句话来总结//但是有的技术员认为不是一定要返回的函数才是闭包,这个我后面会有例子上来

?? ?第一:闭包是一个本地的函数变量,当调用它的函数返回的时候,它仍然是存在的,没有被释放。

?? ?第二:闭包是一个堆栈当函数被返回的时候,该堆栈没有被释放。---闭包的重要作用,保存临时变量

  • 看下面的例子
function?sayHello2(name)?{
??var?text?= 'Hello?'?+ name; //?local?variable--本地变量是一个string对象
??var?sayAlert?= function()?{ alert(text); }
??return?sayAlert;//闭包的标志,返回一个函数,该函数中text仍然是村在的
}
var say2=sayHello2('xx');//将返回的函数赋给say2
say2();//执行say2--其实就是执行sayAlert

再来看下面的这个例子

function?say667()?{
??//?Local?variable?that?ends?up?within?closure
??var?num?= 666;
??var?sayAlert?= function()?{ alert(num); }

??num++;
?return?sayAlert;
}


?

var sayNumba=say667();

sayNumba(); //弹出667

从上面这个例子我么可以看出,本地变量不是复制而是保持其引用在js引擎中,直到外部函数消失

下次,就写个闭包的常见引用吧,遍学习边用博客记录下来,方便自己

?

下面是我看到的一位技术牛人对闭包的看法

This is an attempt to clear up several (possible) misunderstandings about closures that appear in some of the other answers.

  • A closure is not only created when you return an inner function.?In fact, the enclosing function does not need to return at all. You might instead assign your inner function to a variable in an outer scope, or pass it as an argument to another function where it could be used immediately. Therefore, the closure of the enclosing function probably already exists at the time that enclosing function was called since any inner function has access to it as soon as it is called.
  • A closure does not reference a copy of the?old values?of variables in its scope.?The variables themselves are part of the closure, and so the value seen by accessing one of those variables is the latest value at the time it is accessed. This is why inner functions inside of loops can be tricky, since they all access the same outer variables.
  • The "variables" in a closure include named functions?declared (at the top level) within the function. It also includes function arguments. The closure also has access to its containing closure's variables, all the way up to the global scope.
  • Closures use memory, but they don't cause memory leaks?since JavaScript itself cleans up circular structures that have no references. IE memory leaks involving closures are caused by not disconnecting DOM attribute values that reference closures, thus maintaining references to possibly circular structures.

?

  相关解决方案