Leonardo
Leonardo

Reputation: 314

How do I pass a parameter into a JS function without wrap it in an anonymous function?

For a long time I had this question: how do I pass a parameter to a JS function without wrap it in a anonymous function?

Let's see an example:

var
x = 10,
foo = function( num ) {
    console.log("Number: " + num);
};

// This way works, but I wouldn't like to wrap it in an anonymous function
setTimeout(function() {
    foo( x );
}, 1000 );

// Is there a way to pass the 'x' parameter here?
setTimeout( foo, 2000 );

Is there a way to pass a parameter on the second setTimeout call?

Upvotes: 0

Views: 40

Answers (1)

Paul
Paul

Reputation: 141827

In modern Javascript engines (MDN also has a shim that makes this work in IE9 and older):

setTimeout( foo, 2000, x );

or use bind, which is not quite as modern, but still modern enough to have no support in IE8 (again there is a shim on MDN):

setTimeout( foo.bind( null, x ), 2000 );

Replace null with whatever you want this to be in your function if you normally would call that function with a context. In your above example, null works well.

Upvotes: 2

Related Questions