JavaScript - 将参数传递给匿名函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16632136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Passing Arguments to Anonymous Functions
提问by Ryan King
I'm calling an anonymous function:
我正在调用一个匿名函数:
closeSidebar(function() {
alert("function called");
$(this).addClass("current");
setTimeout(function(){openSidebar()}, 300);
});
But $(this)
doesn't work as expected and I need to pass it as an argument into the function. After a bit of research I thought this would work:
但是$(this)
没有按预期工作,我需要将它作为参数传递给函数。经过一番研究,我认为这会奏效:
closeSidebar(function(el) {
$(el).addClass("current");
setTimeout(function(){openSidebar()}, 300);
})(this);
But it doesn't. How do I add arguments to an anonymous function?
但事实并非如此。如何向匿名函数添加参数?
jsFiddle- Click a button on the right, it animates in then calls the function above. When the button has the class "current" it will have a white bar on the left side of the button but the class never changes.
jsFiddle- 单击右侧的按钮,它会在其中设置动画,然后调用上面的函数。当按钮具有“当前”类时,按钮左侧将有一个白条,但该类永远不会改变。
回答by SivaRajini
You can refer below code for passing parametrs in anonymous function.
您可以参考以下代码以在匿名函数中传递参数。
var i, img;
for(i = 0; i < 5; i++)
{
img = new Image();
img.onload = function(someIndex)
{
someFunction(someIndex);
}(i);
img.src = imagePaths[i];
}
Hope u will get some idea.
希望你会有一些想法。
回答by SivaRajini
You can also do this:
你也可以这样做:
closeSidebar(function(el) {
$(el).addClass("current");
setTimeout(function(){openSidebar()}, 300);
}(this));
The arguments need to be passed to the anonymous function itself, not the caller.
参数需要传递给匿名函数本身,而不是调用者。
回答by anomaaly
Use this method for adding arguments:
使用此方法添加参数:
var fn=function() { };
fn.apply(this,arguments);