简体   繁体   English

JavaScript箭头功能

[英]JavaScript arrow functions

I have seen some code that looks like this: 我看到一些看起来像这样的代码:

function printErr(err) {
    console.error(err)
}
request.on('error', err => printErr)

How does that work? 这是如何运作的? I have spent hours trying to figure it out and searching everywhere for it. 我花了好几个小时试图找出它并在各处搜索它。 I know that printErr is an object with a function that is being returned but what is the mechanism that lets it put the err parameter into the function and call it? 我知道printErr是一个带有正在返回的函数的对象但是什么机制让它将err参数放入函数并调用它?

I am thinking along the lines of: 我在想:

function foo(callback){
    callback()
}

request.on('error', err => foo)

But how does it get the arguments? 但它如何得到论点?

This is a short hand for the arrow function. 这是箭头功能的简写。 Whenever there is only one argument we can call it even without parentheses and => represents the return . 只要有one argument ,即使没有parentheses也可以调用它, =>表示return When there is only a single line return we can explicitly use => for returning rather then using return. 当只有一行return我们可以显式地使用=>返回而不是使用return。

 var a=e=>"hey"; console.log(a()) 

This is same as the above 这与上面相同

 var a=(e)=>{return "hey"}; console.log(a()) 

I was confused at first but it was because the code I was analyzing was mistaken. 起初我很困惑,但这是因为我分析的代码是错误的。

to simplify 简化

function print(data) {
    console.log(data)
}

const foo = [1,2,3,4]

foo.forEach(x => print) // will not print and just return undefined.
foo.forEach(x => print(x)) // will print correctly

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

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