![](/img/trans.png)
[英]Why does this cause an “invalid syntax” error with Google's Closure Compiler?
[英]Why no compiler error for this closure function?
我正在阅读 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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.