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

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


当前回答

第一個問題有一個引用:

如果你不能向六岁的人解释,你真的不明白。

这就是我会试图向一个真正的六岁男孩解释的方式:

你知道成年人如何拥有房子,他们称之为房子吗?当一个母亲有孩子时,孩子真的没有任何东西,对吗?但是她的父母拥有房子,所以每当有人问“你的房子在哪里?”孩子可以回答“那房子!”并指向父母的房子。

“关闭”是孩子能够永远(即使在国外)提到自己的家,即使是真正的父母拥有家。

其他回答

第一個問題有一個引用:

如果你不能向六岁的人解释,你真的不明白。

这就是我会试图向一个真正的六岁男孩解释的方式:

你知道成年人如何拥有房子,他们称之为房子吗?当一个母亲有孩子时,孩子真的没有任何东西,对吗?但是她的父母拥有房子,所以每当有人问“你的房子在哪里?”孩子可以回答“那房子!”并指向父母的房子。

“关闭”是孩子能够永远(即使在国外)提到自己的家,即使是真正的父母拥有家。

在JavaScript中,关闭是令人惊叹和独特的,其中变量或论点可用于内部功能,即使外部功能已返回后,它们也会活着。

function getFullName(a, b) {
  return a + b;
}

function makeFullName(fn) {

  return function(firstName) {

    return function(secondName) {

      return fn(firstName, secondName);

    }
  }
}

makeFullName(getFullName)("Stack")("overflow"); // Stackoverflow

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

// 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

有些人非常接近得到简单的解释,然后变得复杂或保持抽象,击败目的,并无法显示一个非常简单的现实世界使用。

关闭有访问包含函数的变量 关闭在自己的内存空间中持久(因此对所有类型的 oop-y 实例物品都是有用的)

function sayHello(name) {
  var text = 'Hello ' + name; // Local variable
  console.log(text);
  var sayAlert = function () {
      alert(text);
  }
  return sayAlert;
}

sayHello(); 
/* This will write 'Hello undefined' to the console (in Chrome anyway), 
but will not alert though since it returns a function handle to nothing). 
Since no handle or reference is created, I imagine a good js engine would 
destroy/dispose of the internal sayAlert function once it completes. */

// Create a handle/reference/instance of sayHello() using the name 'Bob'
sayHelloBob = sayHello('Bob');
sayHelloBob();

// Create another handle or reference to sayHello with a different name
sayHelloGerry = sayHello('Gerry');
sayHelloGerry();

/* Now calling them again demonstrates that each handle or reference contains its own 
unique local variable memory space. They remain in memory 'forever' 
(or until your computer/browser explode) */
sayHelloBob();
sayHelloGerry();

这表明了你应该关于关闭的两个基本概念。

在简单的说法中,我有一个基本函数,我可以创建参考或操作,其中包含独特的数据,留在记忆参考中。我不需要每次我想说别人的名字,我都需要重写函数。

关闭是当内部函数以某种方式为外部函数以外的任何范围提供时创建的。

例子:

var outer = function(params){ //Outer function defines a variable called params
    var inner = function(){ // Inner function has access to the params variable of the outer function
        return params;
    }
    return inner; //Return inner function exposing it to outer scope
},
myFunc = outer("myParams");
myFunc(); //Returns "myParams"