如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?

我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。


当前回答

关闭是通过内部函数可以提到在其外部关闭函数中存在的变量,其母函数已经结束后。

// A function that generates a new function for adding numbers.
function addGenerator( num ) {
    // Return a simple function for adding two numbers
    // with the first number borrowed from the generator
    return function( toAdd ) {
        return num + toAdd
    };
}

// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number.
var addFive = addGenerator( 5 );
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4.
alert( addFive( 4 ) == 9 );

其他回答

关闭是一种功能,它可以从它所定义的环境中获取信息。

对于某些人来说,信息是创造时的环境价值;对于其他人来说,信息是创造时的环境变量。

一个关闭可以想象一个特殊的情况的全球变量 - 与一个私人副本创建仅为功能。

或者它可以被认为是一种方法,环境是对象的具体例子,其属性是环境中的变量。

前者(封闭作为环境)类似于后者,环境复制是前者中的每个函数转移的背景变量,例子变量在后者中形成一个背景变量。

因此,关闭是一种呼叫函数的方式,而无需明确地指定背景为参数或作为方法引用中的对象。

var closure = createclosure(varForClosure);
closure(param1);  // closure has access to whatever createclosure gave it access to,
                  // including the parameter storing varForClosure.

vs

var contextvar = varForClosure; // use a struct for storing more than one..
contextclosure(contextvar, param1);

vs

var contextobj = new contextclass(varForClosure);
contextobj->objclosure(param1);

函数在其定义的对象/函数范围内执行,该函数可以访问在其执行期间在对象/函数中定义的变量。

写字,写字,写字,写字:P

标签:猴子

在上面的例子中,outerFunction 被称为,其次称为 innerFunction. 请注意,outerVar 是如何向 innerFunction 提供的,通过正确警告 outerVar 的值来证明。

标签:猴子

referenceToInnerFunction 设置为 outerFunction(),它简单地返回一个参考到 innerFunction. 当 referenceToInnerFunction 被召回时,它返回 outerVar. 再次,如上所述,这表明 innerFunction 有访问 outerVar,一个变量 outerFunction. 此外,值得注意的是,它保留这个访问,即使 outerFunction 完成执行后。

警告:猴子警告:猴子警告

關閉的兩件事要注意:第一,關閉總是會有其內容功能的最後價值的存取。

函数外( ) 函数( ) 函数( ) 函数( ) 函数( ) 函数( ) 函数( ) 函数( ) 函数( ) 函数( )

关闭是一种功能,即使关闭了父母功能后,也可以访问父母范围。

var add = (function() {
  var counter = 0;
  return function() {
    return counter += 1;
  }
})();

add();
add();
add();
// The counter is now 3

例子解释:

变量添加被指定为自我召唤函数的回报值. 自我召唤函数只运行一次. 它将计算器设置为零(0),并返回函数表达式. 这种方式添加变成函数. “奇妙”部分是它可以在母范围内访问计算器. 这被称为JavaScript关闭。

来源

JavaScript 功能可以访问:

论点本地(即其本地变量和本地功能) 环境,其中包括:全球性,包括DOM在外部功能中的任何东西

请注意,外部功能不需要,尽管它们提供的好处我不在这里讨论。 通过访问其环境中的数据,一个关闭保持数据的生存. 在外部/内部功能的底部,外部功能可以创建本地数据,最终输出,但是,如果任何内部功能(s)在外部功能输出后生存,那么内部功能(s)保持外部功能的位置。

使用全球环境的封闭例子:

当用户点击 VoteUp 按钮时, voteUp_click 函数检查是否是VotedDown == 真实,以确定是否投票或仅仅取消投票。

var isVotedUp = false;
var isVotedDown = false;

function voteUp_click() {
  if (isVotedUp)
    return;
  else if (isVotedDown)
    SetDownVote(false);
  else
    SetUpVote(true);
}

function voteDown_click() {
  if (isVotedDown)
    return;
  else if (isVotedUp)
    SetUpVote(false);
  else
    SetDownVote(true);
}

function SetUpVote(status) {
  isVotedUp = status;
  // Do some CSS stuff to Vote-Up button
}

function SetDownVote(status) {
  isVotedDown = status;
  // Do some CSS stuff to Vote-Down button
}