我看过一些代码,看起来像这样:
function printErr(err) {
console.error(err)
}
request.on('error', err => printErr)这是如何工作的呢?我花了几个小时试图弄清楚它,到处寻找它。我知道printErr是一个带有返回函数的对象,但是是什么机制让它将err参数放入函数并调用它呢?
我的想法大致如下:
function foo(callback){
callback()
}
request.on('error', err => foo)但是它是如何获得参数的呢?
发布于 2019-01-23 15:00:33
这是箭头函数的缩写。当只有one argument时,即使没有parentheses,我们也可以调用它,而=>表示return。当只有一行返回时,我们可以显式地使用=>来返回,而不是使用return。
var a=e=>"hey";
console.log(a())
这与上面的相同
var a=(e)=>{return "hey"};
console.log(a())
发布于 2019-01-24 03:32:23
一开始我很困惑,但这是因为我分析的代码是错误的。
简化
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 correctlyhttps://stackoverflow.com/questions/54321527
复制相似问题