简体   繁体   English

JavaScript中的闭包

[英]Closures in JavaScript

I have a code like this where I am trying to add an event handler to some button. 我有这样的代码,我试图在其中添加事件处理程序到某个按钮。 I would like to use a global variable & store its current value in callback closure & not its reference. 我想使用全局变量并将其当前值存储在回调闭包中,而不是其引用中。

var globalNum="dummy";
function A()
{
  $("#button").click(function()
  {
     $("#button").append(globalNum);
  });
}

globalNum="dummyAgain";

Now if click event is fired what would be added - "dummy" or "dummyAgain" ? 现在,如果触发了点击事件,将会添加什么-“ dummy”或“ dummyAgain”? I believe it would be "dummyAgain" coz for closure global variable's reference is stored. 我相信对于封闭全局变量的引用将被存储为“ dummyAgain”。 I want value to bind. 我想要价值绑定。 I know I can create a local variable inside A which I can initialize with global variable & bind that but is there some other cooler way around too? 我知道我可以在A内创建一个局部变量,可以使用全局变量进行初始化并绑定该变量,但是还有其他更酷的方法吗?

Thanks 谢谢

You are right, it would append dummyAgain . 没错,它将追加dummyAgain You can deal with this by using bind() and send some event data: 您可以使用bind()处理此问题并发送一些事件数据:

var globalNum="dummy";
(function A()
{
  $("#button").bind('click', {localNum: globalNum}, function(e)
  {
     $("#button").append(e.data.localNum);
  });
})();

globalNum="dummyAgain";

Note that I immediately execute the function A , so the click handler gets attached before the value of globalNum changes. 请注意,我立即执行了函数A ,因此单击处理程序在globalNum值更改之前已附加。 As @Andrew points out in his comment, this is the same effect as not using the "wrapping" function A at all. 正如@Andrew在其评论中指出的,这与根本不使用“包装”功能A效果相同。


Same solution without bind : 没有bind相同解决方案:

(function()
 {
  var localNum = globalNum;
  $("#button").click(function()
  {
     $("#button").append(localNum);
  });
})();

Here the anonymous function is useful to capture the the current value globalNum in a local variable. 在这里,匿名函数对于捕获局部变量中的当前值globalNum用。


Update: 更新:

For the sake of completeness (I hope, @Andrew, you don't mind that I put it here). 为了完整起见(我希望@Andrew,您不在乎我将其放在此处)。 The "coolest" way is probably to use a parameter for the function and execute the function immediately with this parameter: “最酷”的方法可能是对函数使用参数,并使用以下参数立即执行函数:

var globalNum="dummy";

(function(globalNum)
 {
  $("#button").click(function()
  {
     $("#button").append(globalNum);
  });
})(globalNum);

globalNum="dummyAgain";

The "trick" is that the name of the parameter and the name of the global variable are the same. “技巧”是参数的名称和全局变量的名称相同。

This is also very often used to refer to some object with a shorter identifier without polluting the global namespace, eg with jQuery: 这也常用于引用具有较短标识符的某些对象,而不会污染全局名称空间,例如jQuery:

(function($) {
    // jQuery == $
})(jQuery)

也许有一些更酷的方法,但是在A中声明局部变量是最简单直接的方法,因此是最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM