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

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


当前回答

const makePlus = 函数(x) { 返回函数(y) { 返回 x + y; } const plus5 = makePlus(5); console.log(plus5(3));

如果JavaScript不知道关闭,会发生什么? 只需由其方法体(基本上是函数通话所做的事情)在最后一行中取代通话,你会得到:

console.log(x + 3);

现在, x 的定义在哪里? 我们没有在当前范围内定义它. 唯一的解决方案是让 plus5 携带其范围(或更好地说,其父母范围)。

其他回答

我需要知道一个按钮被点击了多少次,每次第三点击都会做点什么。

考虑此选项

var element = document.getElementById('按钮'); element.addEventListener(“点击”,(函数() { // init 计算到 0 var 计算 = 0; 返回函数(e) { // <- 这个函数变成点击处理器计算++; // 并将保持访问上述 ` 计算` 如果(计算 === 3) { // 做点什么每第三次 console.log(“第三次是魅力!”); // 恢复 c

简单的单线关闭

//          _______________________Immediately invoked______________________
//         |                                                                |
//         |        Scope retained for use      ___Returned as the____      |
//         |       only by returned function   |    value of func     |     |
//         |             |            |        |                      |     |
//         v             v            v        v                      v     v
var func = (function() { var a = 'val'; return function() { alert(a); }; })();

func();  // Alerts "val"
func.a;  // Undefined

因此,在我们的主要例子中,计算变量包含在关闭室内,并始终可用于活动交易者,因此它保持其状态从点击到点击。

在那里你去;现在你正在完全包容这种行为。

好吧,和一个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

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

const makePlus = 函数(x) { 返回函数(y) { 返回 x + y; } const plus5 = makePlus(5); console.log(plus5(3));

如果JavaScript不知道关闭,会发生什么? 只需由其方法体(基本上是函数通话所做的事情)在最后一行中取代通话,你会得到:

console.log(x + 3);

现在, x 的定义在哪里? 我们没有在当前范围内定义它. 唯一的解决方案是让 plus5 携带其范围(或更好地说,其父母范围)。

我收集了一个互动的JavaScript教程来解释关闭是如何工作的。

下面是其中一个例子:

var create = function (x) {
    var f = function () {
        return x; // We can refer to x here!
    };
    return f;
};
// 'create' takes one argument, creates a function

var g = create(42);
// g is a function that takes no arguments now

var y = g();
// y is 42 here

如果你理解它,你可以简单地解释它,而最简单的方式就是从背景中抽取它,代码一边,甚至编程一边,一个形象的例子会更好。

如果你从外面打电话,你不知道里面有什么,但你知道里面的人会做一个任务,如果你给他们一定的信息,他们可以看到外面,所以他们可以问你外面的东西,并改变这些东西,但你不能改变里面有什么,从外面,你甚至看不到(知道)里面有什么。

对于每个呼叫到一个室内,那个房间的人保留了关于这个特定呼叫的信息记录,他们做得如此好,以至于他们永远不会错过一个呼叫事物与其他呼叫事物。