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

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


当前回答

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

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

其他回答

曾经有过一个洞穴

function caveman {

有一个非常特殊的岩石的人,

var rock = "diamond";

你不能自己拿到岩石,因为它是洞穴的私人洞穴,只有洞穴人知道如何找到和拿到岩石。

return {
    getRock: function() {
        return rock;
    }
};
}

幸运的是,他是一个友好的骑士,如果你愿意等待他的回来,他会很高兴得到它为你。

var friend = caveman();
var rock = friend.getRock();

非常聪明的 Caveman。

在模块模式中,您定义了一个函数,然后立即在所谓的即时启动函数表达(IIFE)中呼叫它。 您在该函数中所写的一切都有私人范围,因为它在关闭中定义,从而允许您在JavaScript中“模拟”隐私。

 var Closure = (function () {
    // This is a closure
    // Any methods, variables and properties you define here are "private"
    // and can't be accessed from outside the function.

    //This is a private variable
    var foo = "";

    //This is a private method
    var method = function(){

    }
})();

另一方面,如果您希望在关闭室外看到一个或多个变量或方法,您可以将其返回对象内部。

var Closure = (function () {
  // This is a closure
  // Any methods, variables and properties you define here are "private"
  // and can't be accessed from outside the function.

  //This is a private variable
  var foo = "";

  //This is a private method
  var method = function(){

  }

  //The method will be accessible from outside the closure
  return {
    method: method
  }

})();

Closure.method();

希望能帮忙......看,

此答案的版本图像: [ 解决]

只是忘记每件事的范围,并记住:当一个变量需要在某个地方,JavaScript不会破坏它。

例子1:

此分類上一篇

例子2:

此分類上一篇

例子3:

关闭是一个代码块,符合三个标准:

它可以作为一个值进行转换,并在需要时由任何拥有这个值的人执行,当时它可以从它创建的背景中提到变量(即它关闭于变量访问,在“关闭”这个词的数学意义上)。

(“关闭”这个词实际上有一个不准确的含义,有些人不认为标准1是定义的一部分。

关闭是功能语言的支柱,但它们也存在于许多其他语言(例如,Java的匿名内部课堂)。你可以用它们做一些酷的事情:它们允许偏离的执行和一些优雅的风格技巧。

由: Paul Cantrell, @ http://innig.net/software/ruby/closures-in-ruby

没有自由变量的功能被称为纯功能。

包含一个或多个自由变量的功能被称为关闭。

var pure = function pure(x){
  return x 
  // only own environment is used
}

var foo = "bar"

var closure = function closure(){
  return foo
  // foo is free variable from the outer environment
}

src: https://leanpub.com/javascriptallongesix/read#leanpub-auto-if-functions-without-free-variables-are-pure-are-closures-impure