如何向某人解释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

其他回答

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

关闭是一种功能,它可以从它所定义的环境中获取信息。

对于某些人来说,信息是创造时的环境价值;对于其他人来说,信息是创造时的环境变量。

一个关闭可以想象一个特殊的情况的全球变量 - 与一个私人副本创建仅为功能。

或者它可以被认为是一种方法,环境是对象的具体例子,其属性是环境中的变量。

前者(封闭作为环境)类似于后者,环境复制是前者中的每个函数转移的背景变量,例子变量在后者中形成一个背景变量。

因此,关闭是一种呼叫函数的方式,而无需明确地指定背景为参数或作为方法引用中的对象。

var closure = createclosure(varForClosure);
closure(param1);  // closure has access to whatever createclosure gave it access to,
                  // including the parameter storing varForClosure.

vs

var contextvar = varForClosure; // use a struct for storing more than one..
contextclosure(contextvar, param1);

vs

var contextobj = new contextclass(varForClosure);
contextobj->objclosure(param1);

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

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

我思考关闭的越多,我会看到它作为一个2步过程: init - 行动

init: pass first what's needed...
action: in order to achieve something for later execution.

到6岁时,我会强调关闭的实际方面:

Daddy: Listen. Could you bring mum some milk (2).
Tom: No problem.
Daddy: Take a look at the map that Daddy has just made: mum is there and daddy is here.
Daddy: But get ready first. And bring the map with you (1), it may come in handy
Daddy: Then off you go (3). Ok?
Tom: A piece of cake!

例如:把一些牛奶带到妈妈(=行动)。首先做好准备,然后把地图(=init)带到这里。

function getReady(map) {
    var cleverBoy = 'I examine the ' + map;
    return function(what, who) {
        return 'I bring ' + what + ' to ' + who + 'because + ' cleverBoy; //I can access the map
    }
}
var offYouGo = getReady('daddy-map');
offYouGo('milk', 'mum');

因为如果你带着一个非常重要的信息(地图),你有足够的知识来执行其他类似的操作:

offYouGo('potatoes', 'great mum');

对于一个开发人员来说,我会在关闭和OOP之间进行平行。 init 阶段类似于在传统 OO 语言中向构建者传达论点; 行动阶段最终是你呼吁实现你想要的方法。

请参见我的另一个答案,描述OO和关闭之间的平行性:

如何在JavaScript中“正确”创建自定义对象?

我相信更短的解释,所以看下面的图像。

此分類上一篇

函数 f1()..> 光红盒

函数 f2()..> 红小盒子

在这里,我们有两个功能,f1()和f2()。f2()是内部到f1()。f1()有一个变量, var x = 10.

在引用函数f1(),f2()可以访问 var x = 10 的值。

这里是代码:

function f1() {
    var x=10;

    function f2() {
        console.log(x)
    }

    return f2

}
f1()

f1 ) 请求:

此分類上一篇