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

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


当前回答

皮诺基奥:1883年关闭(JavaScript前一世纪)

我想这最好可以解释给一个有趣的冒险的6岁男孩......Pinocchio的冒险的一部分,在那里Pinocchio被一个过度的狗鱼吞下。

var tellStoryOfPinocchio = 函数(原始) { // 准备令人兴奋的事情发生 var pinocchioFindsMisterGeppetto; var happyEnding; // 故事开始在那里Pinocchio寻找他的“父亲” var pinocchio = { 名称:‘Pinocchio’,位置:‘在海里’,鼻子长度: 2 }; // 它是一只狗......它是一只鱼...... // 狗鱼出现,但是我

其他回答

下面是我最能给出的Zen答案:

你会期望这个代码做什么?在你运行它之前,在评论中告诉我!我很好奇!

function foo() {
  var i = 1;
  return function() {
    console.log(i++);
  }
}

var bar = foo();
bar();
bar();
bar();

var baz = foo();
baz();
baz();
baz();

现在,在您的浏览器中打开控制台(Ctrl + Shift + I 或 F12,希望)并插入代码并点击 Enter。

如果这个代码打印了你所期望的(JavaScript的新闻 - 忽略“未定义”的结尾),那么你已经有无语的理解。

我把它这样做,因为一旦我意识到这个代码将Foo()的内部函数的例子放在字符串和字符串中,然后通过这些变量呼叫它们,没有别的东西让我感到惊讶。

但如果我错了,并且控制台的输出让你惊讶,让我知道!

维基百科 关闭:

在计算机科学中,关闭是一种函数,以及该函数的非本地名称(自由变量)的参考环境。

技术上,在JavaScript中,每个功能都是一个关闭,它总是有在周围范围内定义的变量访问。

由于JavaScript的范围定义结构是一种功能,而不是像许多其他语言一样的代码区块,我们通常在JavaScript中关闭的意思是与已执行的周围功能中定义的非本地变量的功能。

密封经常用来创建一些隐藏的私人数据的功能(但这并不总是如此)。

var db = (function() {
    // Create a hidden object, which will hold the data
    // it's inaccessible from the outside.
    var data = {};

    // Make a function, which will provide some access to the data.
    return function(key, val) {
        if (val === undefined) { return data[key] } // Get
        else { return data[key] = val } // Set
    }
    // We are calling the anonymous surrounding function,
    // returning the above inner function, which is a closure.
})();

db('x')    // -> undefined
db('x', 1) // Set x to 1
db('x')    // -> 1
// It's impossible to access the data object itself.
// We are able to get or set individual it.

EMS

上面的例子是使用一个匿名函数,一次执行,但它不一定是. 它可以被命名(例如 mkdb)并后续执行,每次被召唤时产生一个数据库函数. 每一个所产生的函数都会有自己的隐藏的数据库对象. 另一个使用例子关闭是当我们不返回一个函数时,但包含多个函数的对象

好吧,和一个6岁的孩子谈话,我可能会使用随后的协会。

想象一下 - 你正在玩你的小兄弟姐妹在整个房子,你正在移动周围与你的玩具,并将其中的一些带到你的哥哥的房间。 过了一会儿,你的哥哥从学校回来,去了他的房间,他锁在里面,所以现在你不能访问玩具留在那里再直接的方式。

比较一个情况,当一个门被草案锁定,没有人在里面(通用功能执行),然后一些当地的火灾发生并燃烧房间(垃圾收集器:D),然后一个新的房间被建造,现在你可以留下其他玩具在那里(新功能例子),但从来没有得到相同的玩具留在第一间房间例子。

对于一个先进的孩子,我会把这样的东西放在下面,这不是完美的,但它让你感觉到它是什么:

function playingInBrothersRoom (withToys) {
  // We closure toys which we played in the brother's room. When he come back and lock the door
  // your brother is supposed to be into the outer [[scope]] object now. Thanks god you could communicate with him.
  var closureToys = withToys || [],
      returnToy, countIt, toy; // Just another closure helpers, for brother's inner use.

  var brotherGivesToyBack = function (toy) {
    // New request. There is not yet closureToys on brother's hand yet. Give him a time.
    returnToy = null;
    if (toy && closureToys.length > 0) { // If we ask for a specific toy, the brother is going to search for it.

      for ( countIt = closureToys.length; countIt; countIt--) {
        if (closureToys[countIt - 1] == toy) {
          returnToy = 'Take your ' + closureToys.splice(countIt - 1, 1) + ', little boy!';
          break;
        }
      }
      returnToy = returnToy || 'Hey, I could not find any ' + toy + ' here. Look for it in another room.';
    }
    else if (closureToys.length > 0) { // Otherwise, just give back everything he has in the room.
      returnToy = 'Behold! ' + closureToys.join(', ') + '.';
      closureToys = [];
    }
    else {
      returnToy = 'Hey, lil shrimp, I gave you everything!';
    }
    console.log(returnToy);
  }
  return brotherGivesToyBack;
}
// You are playing in the house, including the brother's room.
var toys = ['teddybear', 'car', 'jumpingrope'],
    askBrotherForClosuredToy = playingInBrothersRoom(toys);

// The door is locked, and the brother came from the school. You could not cheat and take it out directly.
console.log(askBrotherForClosuredToy.closureToys); // Undefined

// But you could ask your brother politely, to give it back.
askBrotherForClosuredToy('teddybear'); // Hooray, here it is, teddybear
askBrotherForClosuredToy('ball'); // The brother would not be able to find it.
askBrotherForClosuredToy(); // The brother gives you all the rest
askBrotherForClosuredToy(); // Nothing left in there

正如你可以看到的那样,房间里留下的玩具仍然可以通过兄弟访问,不管房间是否被锁定。

你和你的家人住在神话般的Ann Ville城,你有一个朋友住在门旁,所以你打电话给他们,请他们出去玩。

000001(JamiesHouse)

一个月后,你和你的家人从Ann Ville出发到下一个城市,但你和你的朋友仍然保持联系,所以现在你必须对你的朋友居住的城市的区域代码说话,然后说话他们的“正确”号码:

001 000001 (annVille.jamiesHouse)

01 001 000001 (myOldCountry.annVille.jamiesHouse)

事实上,如此可怕,你告诉你从你的老国家的杰米......你有一个好笑话,所以有一天,你和你的家人去度假回到老国家,你去参观你的老城(安·维尔),去参观杰米。

“真的?另一个杰米?在安·维尔?在你的新国家!!!?”“是的......让我们叫他们......”

观点?

关闭是函数被关闭时,函数被定义为名称空间,函数被召唤时是不可变的。

在JavaScript中,它发生时:

定义一个函数在另一个函数内 内部函数在外部函数返回后被召回

// 'name' is resolved in the namespace created for one invocation of bindMessage
// the processor cannot enter this namespace by the time displayMessage is called
function bindMessage(name, div) {

    function displayMessage() {
        alert('This is ' + name);
    }

    $(div).click(displayMessage);
}