Passing a named function to Javascript

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

Currently the only solution I have seems to be a hack, but it is passing an unnamed function that will call a named function.

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

      

Is there a better way to do this?

+3


source to share


4 answers


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

If you want to remove the anonymous function, you can use a function reference with a method instead bind()

. Try the following:



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

      

binding () documentation

+2


source


No, there are several ways to do it, but the way you have it is the most popular. I know this seems like a hack, but it is.

You can also do



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

      

+3


source


You can also just pass a function and use Javascript functions apply

/call

callback(myFunc);

      

where the callback is defined as:

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

      

For more details you can go to the Application Method documentation on MDN Here

0


source


Your function must be assigned to a scoped variable. You can pass it to this variable.

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

      

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

callback(foo);

      

0


source







All Articles