javascript - 为什么这个闭包函数没有编译器错误?
问题描述
我正在阅读 Marijn Haverbeke 的优秀著作《Eloquent JavaScript》。 https://eloquentjavascript.net/
我不明白这个关于未定义闭包number
的示例,但没有错误。
是number
函数还是参数?
没有任何迹象表明number
第二次作为参数传入。
function multiplier(factor) {
return number => number * factor;
}
let twice = multiplier(2);
console.log(twice(5));
// → 10
解决方案
理解闭包是如何工作的已经够难的了,但是当你看到的例子任意混合了一个函数声明和一个箭头函数时——就像这个例子一样——如果你不理解箭头函数是如何工作的,那就更难理解了。
这是一个稍微简单的示例,它不使用箭头函数来显示正在发生的事情。
// `multipler` takes a factor as an argument
function multiplier(factor) {
// It returns a function that - when it's called -
// accepts a number
return function (number) {
// And the return from that function
// is the factor * number
return number * factor;
}
}
// So we call `multipler` with a factor and assign the
// function it returns to our `twice` variable
let twice = multiplier(2);
// We can then call the function assigned
// to `twice` with a number, and the resulting
// return from that function will be factor * number
console.log(twice(5));
就使用该箭头函数的示例而言:
// We pass in a factor to the `multipler`
function multiplier(factor) {
// We return a function that accepts a number
// and returns factor * number
// (I've added parentheses around the number
// parameter to clearly show it)
return (number) => number * factor;
}
// So we call `multipler` with a factor and assign the
// function it returns to our `twice` variable
let twice = multiplier(2);
// We can then call the function assigned
// to `twice` with a number, and the resulting
// return from that function will be factor * number
console.log(twice(5));
推荐阅读
- python - 如何正确地将 lambda 函数应用于数据框列?
- javascript - 将 GET 变量传递给 On Click 函数
- json - 如果 json 字符串中不存在所有属性,则颤振反序列化类
- javascript - 从 VUEX 中的突变中改变特定的状态
- graphdb - 存储库 ID 中的 GraphDB 点?
- python - 获取行的内容(使用 df [ ] 不起作用)
- node.js - Node.js - Parse raw text to JSON using RegEx
- .net - 如何使用 PowerShell 的 FtpWebRequest 类从 FTP 服务器下载文件名中包含井号/哈希符号“#”的文件
- sql - 为什么使用 MERGE 插入多条记录的 SQL Server upsert?
- c - 使用不带参数列表的 execv