匿名函数中的静态变量
我正在尝试模仿 JavaScript 函数上的静态变量,目的如下:
$.fn.collapsible = function() {
triggers = $(this).children('.collapse-trigger');
jQuery.each(triggers, function() {
$(this).click(function() {
collapse = $(this).parent().find('.collapse');
})
})
}
如何保存“折叠”对象,以便不必在每次调用时“找到”它? 我知道使用命名函数我可以做类似“someFunction.myvar =崩溃”的事情,但是像这样的匿名函数怎么样?
谢谢!
I'm trying to mimic static variables on a JavaScript function, with the following purpose:
$.fn.collapsible = function() {
triggers = $(this).children('.collapse-trigger');
jQuery.each(triggers, function() {
$(this).click(function() {
collapse = $(this).parent().find('.collapse');
})
})
}
How do I save the "collapse" object so it doesn't have to be "found" on each call? I know that with named functions I could do something like "someFunction.myvar = collapse", but how about anonymous functions like this one?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您没有当前的函数名称,您可以使用
functioName.myVar = value
或arguments.callee.myVar = value
将变量保存在函数中。arguments.callee
是您当前所在的函数。You can save your variable in the function, using either
functioName.myVar = value
orarguments.callee.myVar = value
if you don't have the current function name.arguments.callee
is the current function you are in.对于匿名函数,您可以使用返回函数的函数。
例如:
应该像魅力一样工作,并且您可以放心静态的初始化代码仅执行一次。
For anonymous function you could use a function that returns a function.
For instance:
Should work like a charm and you're assured initialisation code for statics is only executed once.
似乎可以在其他地方找到这个问题的更好答案关于堆栈溢出。
简而言之,您实际上可以在不污染命名空间的情况下给出匿名函数名称,但仍然允许自引用。
It seems that a better answer to this question is found elsewhere on Stack Overflow.
In short, you can actually give anonymous functions names without polluting the namespace, yet still allow self-referencing.
只要您将函数分配给这样的变量,您就应该能够以
$.fn.collapsible
的形式访问它,从而将变量分配为$.fn.collapsible。 myvar
。As long as you're assigning the function to a variable like that, you should be able to access it as
$.fn.collapsible
, and thus assign variables as$.fn.collapsible.myvar
.