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

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


当前回答

一个六岁的答案(假设他知道什么是函数,什么是变量,以及什么数据):

函数可以返回数据. 从函数可以返回的一种数据是另一个函数. 当该新函数返回时,在创建的函数中使用的所有变量和论点都不会消失. 相反,该母函数“关闭”。 换句话说,没有什么可以看到它的内部,看到它所使用的变量,除了它返回的函数。

function the_closure() {
  var x = 4;
  return function () {
    return x; // Here, we look back inside the_closure for the value of x
  }
}

var myFn = the_closure();
myFn(); //=> 4

另一种非常简单的方式来解释它是从范围来看:

每当你在更大的范围内创建一个较小的范围时,更小的范围总是能够看到更大的范围。

其他回答

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

在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);
}

我知道已经有很多解决方案,但我猜这个小而简单的脚本可以有用来证明这个概念:

// makeSequencer will return a "sequencer" function
var makeSequencer = function() {
    var _count = 0; // not accessible outside this function
    var sequencer = function () {
        return _count++;
    }
    return sequencer;
}

var fnext = makeSequencer();
var v0 = fnext();     // v0 = 0;
var v1 = fnext();     // v1 = 1;
var vz = fnext._count // vz = undefined

孩子们永远不会忘记他们与父母分享的秘密,即使父母离开后。

JavaScript 功能的秘密是私人变量

var parent = function() {
 var name = "Mary"; // secret
}

正如你可以猜测的那样,因为变量每次函数被召唤,没有人会知道它们,必须有一个秘密的地方,它们被存储在那里,它可以被称为秘密室或管道或地方范围,但这并不重要,我们知道它们在某个地方隐藏在记忆中。

但是,在JavaScript中,这是一个非常特殊的事情,在其他功能内创建的功能,也可以知道父母的本地变量,并保持它们,只要他们活着。

var parent = function() {
  var name = "Mary";
  var child = function(childName) {
    // I can also see that "name" is "Mary"
  }
}

因此,只要我们在父母功能,它可以创建一个或多个儿童功能,从秘密位置分享秘密变量。

但可悲的是,如果孩子也是父母功能的私人变量,当父母结束时也会死亡,而秘密也会与他们一起死亡。

所以要活着,孩子必须离开,直到太晚了。

var parent = function() {
  var name = "Mary";
  var child = function(childName) {
    return "My name is " + childName  +", child of " + name; 
  }
  return child; // child leaves the parent ->
}
var child = parent(); // < - and here it is outside 

所以,如果你叫孩子“爱丽丝”,她会回答。

child("Alice") => "My name is Alice, child of Mary"

这就是所有要说的。

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

此外,必须明白,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();

函数和函数的外部范围(语法环境)的参考

函数 汽车(制造商,模型,年,颜色) { 返回 { 到String() { 返回 `${ 制造商} ${ 模型} (${ 年}, ${ 颜色})` } } 组车 = 新车(‘Aston Martin’,‘V8 Vantage’,‘2012’,‘Quantum Silver’) console.log(car.toString())

事件导向的编程

在下面的例子中,所有实施细节都隐藏在即时执行的函数表达式内。 函数标记和 toString 接近私人状态和函数他们需要完成工作。 关闭已使我们能够模块化和包容我们的代码。

例子1

这个例子表明,本地变量在关闭中没有复制:关闭保持了对原始变量的参考。

左边