首页 > 解决方案 > 为什么这个闭包函数没有编译器错误?

问题描述

我正在阅读 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

标签: javascriptclosures

解决方案


理解闭包是如何工作的已经够难的了,但是当你看到的例子任意混合了一个函数声明和一个箭头函数时——就像这个例子一样——如果你不理解箭头函数是如何工作的,那就更难理解了。

这是一个稍微简单的示例,它不使用箭头函数来显示正在发生的事情。

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


推荐阅读