简体   繁体   中英

pass a function as argument in javascript

I am currently solving an exercise and I am facing a problem passing a funcion as an argument to another function. The exercise is: 1.Declare a function which takes two arguments, a and b , and returns the sum of those arguments. var add = function(a,b){return a+b;};

2.Declare the variable calculator and assign it a function which takes three arguments, a,b and c . Inside the body of calculator , invoke the function passed as the argument c , passing as arguments a and b . var calculator = function(a,b,c=add(a,b)) { var invoke = c; console.log(invoke); };

3.invoke calculate passing it the sum function as a third argument. Is it supposed to be like this? calculate(x,y,sum());

when the code is submitted I get the following error: The function calculate should print the result of calling undefined with x and y as arguments;

Can anyone help ?

"Invoke the function c passing as arguments a and b" is a lot of words for c(a,b)

It sounds like the result from the second step should look like:

var calculator = function(a,b,c) { return c(a,b) }

You should understand what's "first class functions". Practically that says that functions are values like everything.

There is a huge different between var a = f() and var a = f . The former invokes , or runs , f and saves the result in a . The later saves f itself in a . That means that a is a function, and you can do a() - which is equal to f() .

If you want to create a function that takes another function as argument (the new function is called higher order function , and the existing one is a callback ), you do it as follows:

function add(a, b) {
  return a + b;
}

function calculator(a, b, callback) {
  return callback(a, b); // Invoke the function stored in `callback` with parameters `a` and `b` and return the result
}

Now I leave the third part for you as an exercise...

Edit:

As of ES6, you can define default parameter of the form function(param = default) , however in order to use add as default value, you should make sure you declare it before calculate so when the js engine see calculate 's declaration it already knows what is add .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM