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

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


当前回答

考虑到这个问题是关于简单地解释它,就像一个6岁的,我的答案是:

“当您在JavaScript中宣布函数时,它将永久地访问在该函数声明之前线上可用的所有变量和函数,该函数和它所访问的所有外部变量和函数都是我们称之为关闭的。

其他回答

关闭是简单的

你可能不应该告诉一个六岁的关闭,但如果你这样做,你可能会说,关闭给了一个能力获得访问一个变量宣布在某些其他功能范围。

此分類上一篇

函数 getA() { var a = []; // 此操作发生后, // 函数返回后 // 函数的 `a` 值设置Timeout(函数() { a.splice(0, 0, 1, 2, 3, 4, 5); }); 返回 a; } var a = getA(); 出(‘什么是‘a` 长度?’); 出(‘a` 长度是‘ + a. 长度’); 设置Timeout(函数() { out(‘No wait...’); 出(‘a` 长度是‘ + a. 长度’); 出(‘OK : <unk> 长度’ )); <pre id="output"></

关闭是一个代码块,符合三个标准:

它可以作为一个值进行转换,并在需要时由任何拥有这个值的人执行,当时它可以从它创建的背景中提到变量(即它关闭于变量访问,在“关闭”这个词的数学意义上)。

(“关闭”这个词实际上有一个不准确的含义,有些人不认为标准1是定义的一部分。

关闭是功能语言的支柱,但它们也存在于许多其他语言(例如,Java的匿名内部课堂)。你可以用它们做一些酷的事情:它们允许偏离的执行和一些优雅的风格技巧。

由: Paul Cantrell, @ http://innig.net/software/ruby/closures-in-ruby

因为所有这些外部变量,由一个经文所指的函数,实际上是其经文所关闭的函数链中的本地变量(全球变量可以假设是某种根函数的本地变量),并且每个函数的单一执行都会产生其本地变量的新例子,因此,每个函数的执行都会返回(或以其他方式转换)。

此外,必须明白,JavaScript中的本地变量不是在滑板框中创建的,而是在滑板上,只有当没有人提到它们时才会被摧毁。当一个函数返回时,其本地变量的参考会减少,但如果在当前执行期间,它们成为关闭的一部分,并且仍然被其经文所定义的函数所提到。

一个例子:

function foo (initValue) {
   //This variable is not destroyed when the foo function exits.
   //It is 'captured' by the two nested functions returned below.
   var value = initValue;

   //Note that the two returned functions are created right now.
   //If the foo function is called again, it will return
   //new functions referencing a different 'value' variable.
   return {
       getValue: function () { return value; },
       setValue: function (newValue) { value = newValue; }
   }
}

function bar () {
    //foo sets its local variable 'value' to 5 and returns an object with
    //two functions still referencing that local variable
    var obj = foo(5);

    //Extracting functions just to show that no 'this' is involved here
    var getValue = obj.getValue;
    var setValue = obj.setValue;

    alert(getValue()); //Displays 5
    setValue(10);
    alert(getValue()); //Displays 10

    //At this point getValue and setValue functions are destroyed
    //(in reality they are destroyed at the next iteration of the garbage collector).
    //The local variable 'value' in the foo is no longer referenced by
    //anything and is destroyed too.
}

bar();

我认为值得回头迈出一步,并考虑一个更普遍的“关闭”概念 - 所谓的“加入运营商”。

在数学中,“加入”操作员是部分命令集中的一个函数,返回最小的对象,大于或等于其论点。在符号中,加入 [a,b] = d 如 d >= a 和 d >= b,但没有一个 e 如 d > e >= a 或 d > e >= b。

因此,加入给你最小的东西“大”比部分。

现在,请注意,JavaScript Scopes 是一个部分安排的结构,所以有一个敏感的概念加入,特别是,一个加入 Scopes 的最小范围比原始 Scopes 大。

因此,对变量A、B、C的关闭是最小的范围(在您的程序的细节中!)将A、B、C带入范围。

我收集了一个互动的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