Bala
Bala

Reputation: 11244

How to call a function with a function as parameter?

As a beginner in Javascript, I am trying to call a function whose parameter is a function.But I get this error.

function execute(f) {
  f();
}

var m = function(x) { return x * x };
m(8)                          #=> returns 64    
execute(m(8))                 #=>  Uncaught TypeError: number is not a function

I guess function execute is executing m(8) before exercising its body, therefore the call becomes execute(64). If so, how do I go about passing a function with a parameter?

Upvotes: 1

Views: 78

Answers (2)

Matthew Mcveigh
Matthew Mcveigh

Reputation: 5685

You can use bind to partially apply 8 to m:

function execute(f) {
  f();
}

var m = function(x) { return x * x };

execute(m.bind(null, 8))  

Upvotes: 2

Denys Séguret
Denys Séguret

Reputation: 382150

You'll have to pass them as separate parameters and use call or apply.

For example :

function execute(f, args) {
   return f.apply(null, args);
}

var m = function(x) { return x * x };
m(8)                            
execute(m, [8])

Now, let's suppose you want to have functions taking any number of arguments, and you don't want to bother with making an array. Then it's a little more fun :

function execute() {
  return arguments[0].apply(null, [].slice.call(arguments, 1));
}

var m = function(x,y) { return x * y };
console.log(m(8, 4))                  
console.log(execute(m, 8, 4))

Upvotes: 2

Related Questions