簡體   English   中英

為什么這個閉包函數沒有編譯器錯誤?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM