简体   繁体   English

如何将值传递给作为参数的函数

[英]How to pass value into function that is a parameter

Hello I've come across this piece of code and I have no idea how it works. 您好,我遇到过这段代码,我不知道它是如何工作的。

function firstFunction(something, else){
     //stuff being done
     return something;
}

var myFunction = firstFunction(function(a,b){
    return a*b;
},'car');

So I am fairly new to Javascript so I'll just say it is, a really confusing language. 因此,我对Java语言还很陌生,所以我只想说它是一种非常令人困惑的语言。 I understand I am declaring a variable that is assigning the firstFunction to itself and passing some noname function as first parameter and a String as a second one. 我知道我在声明一个变量,该变量将firstFunction分配给它自己,并传递一些noname函数作为第一个参数,并传递一个String作为第二个参数。

How do I go about passing the arguments into that noname functions? 如何将参数传递给该noname函数?

Yes, your assessment is pretty much correct, although the code has a syntax error because you can use else as an identifier. 是的,尽管代码存在语法错误,但是您可以使用else作为标识符,因此您的评估几乎是正确的。 These are referred to as anonymous functions . 这些被称为匿名函数

Function in JavaScript can be used as parameter values or return values just as easily as any other value. JavaScript中的函数可以用作参数值或返回值,就像其他任何值一样容易。 This is what makes them first-class citizens of the language. 这就是使他们成为语言的一等公民的原因。

The anonymous function you pass in to firstFunction is returned and assigned to myFunction so if you want to call it, you can simply do this: 您传递给firstFunction的匿名函数将被返回并分配给myFunction因此,如果要调用它,只需执行以下操作:

var result = myFunction(4, 5); // 20

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

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