JavaScript 中的闭包
我有这样的代码,我试图将事件处理程序添加到某个按钮。我想使用全局变量 &将其当前值存储在回调闭包中不是它的参考。
var globalNum="dummy";
function A()
{
$("#button").click(function()
{
$("#button").append(globalNum);
});
}
globalNum="dummyAgain";
现在,如果单击事件被触发,将添加什么 - “dummy”或“dummyAgain”? 我相信这将是“dummyAgain”,因为存储了闭包全局变量的引用。我想要绑定价值。 我知道我可以在 A 内部创建一个局部变量,我可以用全局变量 & 初始化它。绑定它,但是还有其他更酷的方法吗?
谢谢
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" ?
I believe it would be "dummyAgain" coz for closure global variable's reference is stored. 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?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的,它会附加dummyAgain。您可以使用
bind()
来处理此问题并发送一些事件数据:请注意,我立即执行函数
A
,因此点击处理程序在globalNum
值更改之前附加。正如 @Andrew 在他的评论中指出的,这与根本不使用“包装”函数A
的效果相同。没有
bind
的相同解决方案:这里匿名函数可用于捕获局部变量中的当前值
globalNum
。更新:
为了完整起见(我希望@Andrew,你不介意我把它放在这里)。 “最酷”的方式可能是为函数使用一个参数,并使用该参数立即执行该函数:
“技巧”是参数的名称和全局变量的名称相同。
这也经常用于引用一些具有较短标识符的对象,而不会污染全局名称空间,例如使用 jQuery:
You are right, it would append dummyAgain. You can deal with this by using
bind()
and send some event data:Note that I immediately execute the function
A
, so the click handler gets attached before the value ofglobalNum
changes. As @Andrew points out in his comment, this is the same effect as not using the "wrapping" functionA
at all.Same solution without
bind
:Here the anonymous function is useful to capture the the current value
globalNum
in a local variable.Update:
For the sake of completeness (I hope, @Andrew, you don't mind that I put it here). The "coolest" way is probably to use a parameter for the function and execute the function immediately with this parameter:
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, e.g. with jQuery:
也许有一些更酷的方法,但在 A 内部声明局部变量是最简单、最直接的方法,因此也是最好的方法。
Maybe there is some cooler way, but declaring a local variable inside A is the most simple and direct way, hence the best.