简体   繁体   English

为什么这个闭包函数没有编译器错误?

[英]Why no compiler error for this closure function?

I am reading Marijn Haverbeke's excellent book, "Eloquent JavaScript".我正在阅读 Marijn Haverbeke 的优秀著作“Eloquent JavaScript”。 https://eloquentjavascript.net/ https://eloquentjavascript.net/

I do not understand this example on closures where number is not defined, yet there is no error.我不明白这个关于没有定义number闭包的例子,但没有错误。

Is number a function or a parameter? number是函数还是参数?

There is nothing to indicate that number is passed in as parameter the second time.没有任何迹象表明第二次将number作为参数传入。

function multiplier(factor) {
  return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));
// → 10

Understanding how closures work is hard enough but when the example you're looking at arbitrarily mixes function declarations with an arrow function - as this one does - if you don't understand how arrow functions work it makes it more difficult to understand.理解闭包的工作原理已经够难了,但是当您正在查看的示例将函数声明与箭头函数任意混合时 - 就像这个一样 - 如果您不了解箭头函数的工作原理,它会使理解变得更加困难。

Here's a slightly easier example that doesn't use an arrow function to show what's going on.这是一个稍微简单的示例,它不使用箭头函数来显示正在发生的事情。

 // `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));

In terms of the example using that arrow function:就使用该箭头函数的示例而言:

 // 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.

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