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

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


当前回答

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

其他回答

我确信,爱因斯坦没有直接期望我们选择任何异常的脑震动的东西,并在六岁时与无用的尝试,让这些“疯狂”(甚至更糟糕的是他们)的东西到他们的童年头脑:)如果我六岁,我不会喜欢这样的父母,也不会与这样的无聊的慈善家建立友谊,对不起。

无论如何,对于婴儿,关闭只是一个拥抱,我猜,无论你如何试图解释:)当你拥抱一个朋友的,然后你两种分享你男孩现在有什么东西。

我真的不知道如何向5至6岁的婴儿解释,我也不认为他们会欣赏任何JavaScript代码剪辑,如:

function Baby(){
    this.iTrustYou = true;
}

Baby.prototype.hug = function (baby) {
    var smiles = 0;

    if (baby.iTrustYou) {
        return function() {
            smiles++;
            alert(smiles);
        };
    }
};

var
   arman = new Baby("Arman"),
   morgan = new Baby("Morgana");

var hug = arman.hug(morgan);
hug();
hug();

只为儿童:

关闭是拥抱

波格飞了

亲吻是微妙的!:)

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

一个关闭是内部函数在其外部函数中有变量的访问,这可能是最简单的单线解释,你可以获得关闭。

关闭是通过内部函数可以提到在其外部关闭函数中存在的变量,其母函数已经结束后。

// A function that generates a new function for adding numbers.
function addGenerator( num ) {
    // Return a simple function for adding two numbers
    // with the first number borrowed from the generator
    return function( toAdd ) {
        return num + toAdd
    };
}

// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number.
var addFive = addGenerator( 5 );
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4.
alert( addFive( 4 ) == 9 );