Search code examples
javascriptjqueryjquery-callbackasynchronous-javascript

Passing a named function in Javascript


How do you pass a named function with parameters without calling it.

Right now the only solution I have seems like a hack but it is to pass an unnamed function that will call the named function.

callback(function(){foo(params);})

Is there a better way of doing this?


Solution

  • The code that you have now, which wraps the call in another anonymous function is perfectly fine, and is a widely used pattern in Javascript.

    If you wish to remove the anonymous function, you could instead use the reference to the function with the bind() method. Try this:

    callback(foo.bind(this, params));
    

    bind() documentation