如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
函数在其定义的对象/函数范围内执行,该函数可以访问在其执行期间在对象/函数中定义的变量。
写字,写字,写字,写字:P
其他回答
能否向五岁男孩解释关闭?
我仍然认为谷歌的解释工作得很好,简要:
/*
* 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#问题
函数和函数的外部范围(语法环境)的参考
函数 汽车(制造商,模型,年,颜色) { 返回 { 到String() { 返回 `${ 制造商} ${ 模型} (${ 年}, ${ 颜色})` } } 组车 = 新车(‘Aston Martin’,‘V8 Vantage’,‘2012’,‘Quantum Silver’) console.log(car.toString())
事件导向的编程
在下面的例子中,所有实施细节都隐藏在即时执行的函数表达式内。 函数标记和 toString 接近私人状态和函数他们需要完成工作。 关闭已使我们能够模块化和包容我们的代码。
例子1
这个例子表明,本地变量在关闭中没有复制:关闭保持了对原始变量的参考。
左边
最简单、最短、最容易理解的答案:
关闭是一个代码块,每个行都可以用相同的变量名称引用相同的变量集。
如果“这”意味着与它在其他地方做什么不同,那么你知道它是两个不同的关闭。
关闭是简单的
你可能不应该告诉一个六岁的关闭,但如果你这样做,你可能会说,关闭给了一个能力获得访问一个变量宣布在某些其他功能范围。
此分類上一篇
函数 getA() { var a = []; // 此操作发生后, // 函数返回后 // 函数的 `a` 值设置Timeout(函数() { a.splice(0, 0, 1, 2, 3, 4, 5); }); 返回 a; } var a = getA(); 出(‘什么是‘a` 长度?’); 出(‘a` 长度是‘ + a. 长度’); 设置Timeout(函数() { out(‘No wait...’); 出(‘a` 长度是‘ + a. 长度’); 出(‘OK : <unk> 长度’ )); <pre id="output"></
因为所有这些外部变量,由一个经文所指的函数,实际上是其经文所关闭的函数链中的本地变量(全球变量可以假设是某种根函数的本地变量),并且每个函数的单一执行都会产生其本地变量的新例子,因此,每个函数的执行都会返回(或以其他方式转换)。
此外,必须明白,JavaScript中的本地变量不是在滑板框中创建的,而是在滑板上,只有当没有人提到它们时才会被摧毁。当一个函数返回时,其本地变量的参考会减少,但如果在当前执行期间,它们成为关闭的一部分,并且仍然被其经文所定义的函数所提到。
一个例子:
function foo (initValue) {
//This variable is not destroyed when the foo function exits.
//It is 'captured' by the two nested functions returned below.
var value = initValue;
//Note that the two returned functions are created right now.
//If the foo function is called again, it will return
//new functions referencing a different 'value' variable.
return {
getValue: function () { return value; },
setValue: function (newValue) { value = newValue; }
}
}
function bar () {
//foo sets its local variable 'value' to 5 and returns an object with
//two functions still referencing that local variable
var obj = foo(5);
//Extracting functions just to show that no 'this' is involved here
var getValue = obj.getValue;
var setValue = obj.setValue;
alert(getValue()); //Displays 5
setValue(10);
alert(getValue()); //Displays 10
//At this point getValue and setValue functions are destroyed
//(in reality they are destroyed at the next iteration of the garbage collector).
//The local variable 'value' in the foo is no longer referenced by
//anything and is destroyed too.
}
bar();