简体   繁体   English

在javascript中传递一个函数作为参数

[英]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.练习是: 1. 声明一个函数,它接受两个参数ab ,并返回这些参数的总和。 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 . 2.声明变量计算器并为其分配一个函数,该函数接受三个参数a,b 和 c Inside the body of calculator , invoke the function passed as the argument c , passing as arguments a and b .计算器的主体内,调用作为参数c传递的函数,作为参数ab传递。 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. 3.invoke 计算将sum函数作为第三个参数传递给它。 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;提交代码时,我收到以下错误:函数计算应打印以 x 和 y 作为参数调用 undefined 的结果;

Can anyone help ?任何人都可以帮忙吗?

"Invoke the function c passing as arguments a and b" is a lot of words for c(a,b) “调用作为参数 a 和 b 传递的函数 c”是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 . var a = f()var a = f之间存在巨大差异。 The former invokes , or runs , f and saves the result in a .前者调用运行f并将结果保存在a The later saves f itself in a .后者将f自身保存在a That means that a is a function, and you can do a() - which is equal to f() .这意味着a是一个函数,您可以执行a() - 它等于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 .从 ES6 开始,您可以定义表单function(param = default)默认参数,但是为了使用add作为默认值,您应该确保在calculate之前声明它,以便当 js 引擎看到calculate的声明时它已经知道什么是add

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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