Mozilla Developer Network的嵌套函数和闭包的描述中缺少什么?

时间:2016-11-26 18:11:27

标签: javascript function closures

我觉得它缺少一些东西。这是:

嵌套函数和闭包

您可以在函数中嵌套函数。嵌套(内部)函数对其包含(外部)函数是私有的。它也形成了一个封闭。闭包是一个表达式(通常是一个函数),它可以将自由变量与绑定这些变量的环境(“关闭”表达式)放在一起。

由于嵌套函数是闭包,这意味着嵌套函数可以“继承”其包含函数的参数和变量。换句话说,内部函数包含外部函数的范围。

总结:

  • 只能从外部语句中访问内部函数 功能
  • 内部函数形成一个闭包:内部函数可以使用外部函数的参数和变量,而外部函数则可以 函数不能使用内部的参数和变量 功能

以下示例显示了嵌套函数:

function addSquares(a,b) {
  function square(x) {
    return x * x;
  }
  return square(a) + square(b);
}
a = addSquares(2,3); // returns 13
b = addSquares(3,4); // returns 25
c = addSquares(4,5); // returns 41

由于内部函数形成一个闭包,你可以调用外部函数并为外部函数和内部函数指定参数:

function outside(x) {
  function inside(y) {
    return x + y;
  }
  return inside;
}
fn_inside = outside(3); // Think of it like: give me a function that adds 3 to whatever you give it
result = fn_inside(5); // returns 8
result1 = outside(3)(5); // returns 8

1 个答案:

答案 0 :(得分:1)

Closures are definitely a topic that is confusing at first, but really it boils down to this:

  1. ANYTIME you have a nested function, you technically have a closure.

  2. Just because you have a closure doesn't necessarily mean that your code will be affected in any significant way.

3. When a nested function relies on variables declared in a higher function (ancestor function) AND the nested function will have a lifetime that is LONGER than the function where those relied on variables were declared, you have a closure situation that needs understanding.

Those variables (used in the nested function, but declared in the higher order function, a.ka. free variables) cannot be garbage collected when the function in which they were declared completes because they are needed by the nested function which will outlive its parent/ancestor. This "outliving" can be caused by the nested function being returned to an even higher order caller by the nested function's parent or the nested function is assigned to another object (like a DOM object).

When this happens, a closure is created around the free variable and that variable's scope is now shared by any other in-memory function that relies on it as well. This causes a shared scope and is usually where confusion by a function that was supposed to get its own value does not. In those cases, modifying the inner function to receive a COPY of the ancestor's free variable can solve this confusion.