Ryan King
Ryan King

Reputation: 3696

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. 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. 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.

Upvotes: 2

Views: 13220

Answers (3)

SivaRajini
SivaRajini

Reputation: 7375

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.

Upvotes: 5

user1508519
user1508519

Reputation:

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.

Upvotes: 4

anomaaly
anomaaly

Reputation: 841

Use this method for adding arguments:

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

Upvotes: 1

Related Questions