简体   繁体   English

JavaScript - 将参数传递给匿名函数

[英]JavaScript - Passing Arguments to Anonymous Functions

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. $(this)不能按预期工作,我需要将它作为参数传递给函数。 After a bit of research I thought this would work: 经过一番研究后,我认为这样可行:

            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. jsFiddle - 单击右侧的按钮,它会动画然后调用上面的函数。 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. 当按钮具有“当前”类时,按钮左侧将有一个白色条,但类永远不会改变。

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. 希望你能得到一些想法。

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. 参数需要传递给匿名函数本身,而不是调用者。

Use this method for adding arguments: 使用此方法添加参数:

var fn=function() { };
fn.apply(this,arguments);

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

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