Kevin Test
Kevin Test

Reputation: 133

How to run an anonymous function that was given as parameter

I know i can have a function as a parameter in javascript. I can also run that function that was given as a parameter. Here's an example:

function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction();
}

What if i wanna give an anonymous function, how will this run inside the outer function.

For example with a function like

setTimeout(function(){
})

How is this anonymous function directly run without a name?

Upvotes: 3

Views: 80

Answers (2)

yunzen
yunzen

Reputation: 33439

Maybe this makes it clearer?

function callFunction(param1, callbackfunction) {
  console.log('callFunction', param1)
  //do processing here
  callbackfunction(param1);
}

function myCustomCallback(param) {
  console.log('myCustomCallback', param)
}

setTimeout(callFunction.bind(this, 'one', myCustomCallback ), 1000)

setTimeout(callFunction.bind(this, 'two', function(p) {alert(p)} ), 2000)

Upvotes: 2

Quentin
Quentin

Reputation: 943564

You don't need a name to call a function. Names are only useful for use in a debugging tool (e.g. when examining a stack trace).

To call a function you need an expression that resolves as the function, which you can follow with ().

You're passing the function as the first argument to setTimeout, so it gets stored in the first parameter of that function. setTimeout's internals then call it.

You do the same with your code, only it is the second argument.

myfunction("some param", function () { /* ... */ }) ;

Upvotes: 8

Related Questions