如何向某人解释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 ) 请求:

此分類上一篇

其他回答

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

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

我认为值得回头迈出一步,并考虑一个更普遍的“关闭”概念 - 所谓的“加入运营商”。

在数学中,“加入”操作员是部分命令集中的一个函数,返回最小的对象,大于或等于其论点。在符号中,加入 [a,b] = d 如 d >= a 和 d >= b,但没有一个 e 如 d > e >= a 或 d > e >= b。

因此,加入给你最小的东西“大”比部分。

现在,请注意,JavaScript Scopes 是一个部分安排的结构,所以有一个敏感的概念加入,特别是,一个加入 Scopes 的最小范围比原始 Scopes 大。

因此,对变量A、B、C的关闭是最小的范围(在您的程序的细节中!)将A、B、C带入范围。

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

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

/*
*    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#问题

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

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

这个答案是这个YouTube视频JavaScript关闭的总结。

关闭只是保持其私人变量的状态的国家功能。

此分類上一篇

但现在有情况下,我们希望保持这个功能状态,即JavaScript关闭会使用。 关闭是内部函数的功能,如下代码所示的返回通话。

此分類上一篇

function Counter() {
           var counter = 0;

           var Increment = function () {
               counter++;
               alert(counter);
           }
           return {
               Increment
           }
       }

var x = Counter(); // get the reference of the closure
x.Increment(); // Displays 1
x.Increment(); // Display 2 ( Maintains the private variables)

但现在最大的问题是如何使用这种可靠的功能。 可靠的功能是构建区块,以实施OP概念,如抽象、包容和创建自我包含的模块。

因此,任何你想要的包容,你可以把它作为私人和事物被曝光给公众应该放回声明。 此外,这些组件是自我包含的隔离物体,所以它们不会污染全球变量。

遵循 OOP 原则的对象是自我包含的,遵循抽象,遵循包容等。

此分類上一篇