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

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


当前回答

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

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

其他回答

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

例子:

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"

JavaScript 功能可以访问:

论点本地(即其本地变量和本地功能) 环境,其中包括:全球性,包括DOM在外部功能中的任何东西

请注意,外部功能不需要,尽管它们提供的好处我不在这里讨论。 通过访问其环境中的数据,一个关闭保持数据的生存. 在外部/内部功能的底部,外部功能可以创建本地数据,最终输出,但是,如果任何内部功能(s)在外部功能输出后生存,那么内部功能(s)保持外部功能的位置。

使用全球环境的封闭例子:

当用户点击 VoteUp 按钮时, voteUp_click 函数检查是否是VotedDown == 真实,以确定是否投票或仅仅取消投票。

var isVotedUp = false;
var isVotedDown = false;

function voteUp_click() {
  if (isVotedUp)
    return;
  else if (isVotedDown)
    SetDownVote(false);
  else
    SetUpVote(true);
}

function voteDown_click() {
  if (isVotedDown)
    return;
  else if (isVotedUp)
    SetUpVote(false);
  else
    SetDownVote(true);
}

function SetUpVote(status) {
  isVotedUp = status;
  // Do some CSS stuff to Vote-Up button
}

function SetDownVote(status) {
  isVotedDown = status;
  // Do some CSS stuff to Vote-Down button
}

能否向五岁男孩解释关闭?

我仍然认为谷歌的解释工作得很好,简要:

/*
*    When a function is defined in another function and it
*    has access to the outer function's context even after
*    the outer function returns.
*
* An important concept to learn in JavaScript.
*/

function outerFunction(someNum) {
    var someString = 'Hey!';
    var content = document.getElementById('content');
    function innerFunction() {
        content.innerHTML = someNum + ': ' + someString;
        content = null; // Internet Explorer memory leak for DOM reference
    }
    innerFunction();
}

outerFunction(1);​

此分類上一篇

答:C#问题

答案:这个答案是写的,当问题是:

正如老阿尔伯特所说:“如果你不能向一个六岁的人解释,你真的不明白自己。 好吧,我试图向一个27岁的朋友解释JS的关闭,并且完全失败了。


一时一刻:

有一位公主......

function princess() {

她在一个充满冒险的奇妙世界中生活,她遇到了她的魅力王子,围绕着一个独角兽的世界,战斗的龙,遇到了谈话的动物,以及许多其他幻想的东西。

    var adventures = [];

    function princeCharming() { /* ... */ }

    var unicorn = { /* ... */ },
        dragons = [ /* ... */ ],
        squirrel = "Hello!";

    /* ... */

    return {

她经常会告诉他们她作为公主的最新惊人的冒险。

        story: function() {
            return adventures[adventures.length - 1];
        }
    };
}

但是,他们只会看到一个小女孩。

var littleGirl = princess();

关于魔法和幻想的故事。

littleGirl.story();

即使成年人知道真正的公主,他们永远不会相信单身或龙,因为他们永远不会看到它们。

这是一个真正的公主,里面有一个小女孩。

雖然在網路上有許多美麗的JavaScript關閉定義,但我試圖開始用我最喜歡的關閉定義來解釋我的六歲朋友,這幫助我更好地理解關閉。

关闭是一种内部功能,它可以访问外部(关闭)函数的变量 - 范围链. 关闭有三个范围链:它可以访问自己的范围(在其曲线手<unk>之间定义的变量),它可以访问外部函数的变量,并且可以访问全球变量。

关闭是指独立(自由)变量的函数,换句话说,关闭中定义的函数“记得”它所创造的环境。

关闭的用途:

关闭是有用的隐藏功能的实施,同时仍然揭示界面。

您可以使用关闭在 JavaScript 中模拟嵌入式概念。

關閉的例子:

function makeAdder(x) {
    return function(y) {
        return x + y;
    };
}

var add5 = makeAdder(5);
var add10 = makeAdder(10);

console.log(add5(2));  // 7
console.log(add10(2)); // 12

function makeAdder(x) {
    return {
        add: function(y){
            return x + y;
        }
    }
}

var add5 = makeAdder(5);
console.log(add5.add(2));//7

var add10 = makeAdder(10);
console.log(add10.add(2));//12

例子3:在jQuery中关闭

$(function(){
    var name="Closure is easy";
    $('div').click(function(){
        $('p').text(name);
    });
});

有用的链接:

感谢上面的链接,这有助于我更好地理解和解释关闭。