3

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?

Qasim Ahmed
  • 177
  • 1
  • 10

4 Answers4

3

Nope, there are a couple of ways to do it but the way you have it is the most popular. I know it feels hacky but that's the way it is.

You could also do

callback(foo.bind(this, params));
phuzi
  • 8,111
  • 3
  • 24
  • 43
2

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

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
  • I really seem to like the bind. It seems intuitive and elegant. Although I worry my code might be less understandable, or that I do not fully grasp what is going on in the background. From what I understand bind will just create an anonymous function, and copy paste the body of the "target bound function" to the new anonymous function. Is that right? Are there any caveats to using bind()? – Qasim Ahmed Jul 03 '15 at 16:01
0

You can also just pass the function and use the Javascript apply/call functions

callback(myFunc);

where callback is defined as:

function callback(func, params) {
    func.apply(null, params);
}

For more detail you can go into the Apply method documentation in MDN Here

MiltoxBeyond
  • 2,545
  • 1
  • 11
  • 12
0

Your function should be assigned to a scoped variable. You can pass it in with that variable.

var func = function(){ foo(params); }
callback(func);

If you were just trying to call foo directly, just pass that in.

callback(foo);