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

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


当前回答

我思考关闭的越多,我会看到它作为一个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中“正确”创建自定义对象?

其他回答

这里是一个简单的实时场景,只需阅读它,你会明白我们如何在这里使用关闭(看看座位数量如何变化)。

此前所解释的所有其他例子,也很好地理解这个概念。

function movieBooking(movieName) {
    var bookedSeatCount = 0;
    return function(name) {
        ++bookedSeatCount ;
        alert( name + " - " + movieName + ", Seat - " + bookedSeatCount )
    };
};

var MI1 = movieBooking("Mission Impossible 1 ");
var MI2 = movieBooking("Mission Impossible 2 ");

MI1("Mayur");
// alert
// Mayur - Mission Impossible 1, Seat - 1

MI1("Raju");
// alert
// Raju - Mission Impossible 1, Seat - 2

MI2("Priyanka");
// alert
// Raja - Mission Impossible 2, Seat - 1

function sing(person) {

    var firstPart = "There was " + person + " who swallowed ";

    var fly = function() {
        var creature = "a fly";
        var result = "Perhaps she'll die";
        alert(firstPart + creature + "\n" + result);
    };

    var spider = function() {
        var creature = "a spider";
        var result = "that wiggled and jiggled and tickled inside her";
        alert(firstPart + creature + "\n" + result);
    };

    var bird = function() {
        var creature = "a bird";
        var result = "How absurd!";
        alert(firstPart + creature + "\n" + result);
    };

    var cat = function() {
        var creature = "a cat";
        var result = "Imagine That!";
        alert(firstPart + creature + "\n" + result);
    };

    fly();
    spider();
    bird();
    cat();
}

var person="an old lady";

sing(person);

指示

我没有时间去购物,所以函数需要知道我们在冰箱里有什么来做出决定。 每个成分都有不同的烹饪时间,我们希望所有的东西都被机器人同时加热。 我们需要提供函数与我们喜欢的数据,函数可以“说话”到冰箱,函数可以控制机器人。

function cookMeal() {  /*  STUFF INSIDE THE FUNCTION  */  }

function sing(person) {  /* STUFF INSIDE THE FUNCTION */  }

因此,这个功能可能与歌曲有关系,可能需要一些关于一个人的数据。

现在,在函数歌(),接近代码的结尾是线

var person="an old lady";

全球变量:人是一个全球变量,这意味着如果你将其值从“老太太”变成“年轻人”,这个人将继续是年轻人,直到你决定再次改变它,而代码中的任何其他功能可以看到它是一个年轻人。

sing(person);

这条线叫这个功能,就好像它叫一个狗。

关闭后,线路来了。

fly();
spider();
bird();
cat();

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

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

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

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

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

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

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

我喜欢Kyle Simpson的关闭定义:

关闭是函数能够记住和访问其语法范围,即使该函数在其语法范围之外运行。

语法范围是当一个内部范围能够访问其外部范围时。

此分類上一篇: You Don't Know JS: Scopes & Closures

function foo() {
  var a = 2;

  function bar() {
    console.log( a );
  }
  return bar;
}

function test() {
  var bz = foo();
  bz();
}

// prints 2. Here function bar referred by var bz is outside 
// its lexical scope but it can still access it
test(); 

在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