如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
对于一个六岁的...
你知道什么是物体吗?
物品是具有属性和物品的物品。
關閉的最重要的事情之一是,它們讓你在JavaScript中創建對象. 在JavaScript中的對象只是功能和關閉,讓JavaScript在創建後儲存對象的屬性價值。
物品非常有用,并保持一切顺利和有组织,不同物品可以做不同的工作,工作物品可以做复杂的事情。
幸运的是,JavaScript有创建对象的关闭,否则一切都会变成一个可怕的噩梦。
其他回答
我知道已经有很多解决方案,但我猜这个小而简单的脚本可以有用来证明这个概念:
// makeSequencer will return a "sequencer" function
var makeSequencer = function() {
var _count = 0; // not accessible outside this function
var sequencer = function () {
return _count++;
}
return sequencer;
}
var fnext = makeSequencer();
var v0 = fnext(); // v0 = 0;
var v1 = fnext(); // v1 = 1;
var vz = fnext._count // vz = undefined
(我没有考虑到6年前的事情。
在JavaScript等语言中,您可以将函数作为参数转移到其他函数(函数是第一级公民的语言),您往往会发现自己正在做这样的事情:
var name = 'Rafael';
var sayName = function() {
console.log(name);
};
你可以看到, sayName 没有定义的名称变量,但它使用的名称值被定义在 sayName 之外(在母范围内)。
functionThatTakesACallback(sayName);
请注意:
接下来会发生什么? 参考错误:未定义的名称?
因此: 即使名称不在函数 sayName 将被召唤的范围内(函数ThatTakesACallback 内), sayName 可以访问与 sayName 相关的关闭中捕获的名称值。
───
函数在其定义的对象/函数范围内执行,该函数可以访问在其执行期间在对象/函数中定义的变量。
写字,写字,写字,写字:P
好吧,6岁的关闭粉丝,你想听到最简单的关闭例子吗?
让我们想象下一个情况:司机坐在车里,那辆车在飞机内,飞机在机场,司机的能力在车外,但在飞机内,即使飞机离开机场,也是一个关闭。
这就是我如何将我的飞机故事转换为代码。
飞机 = 函数(默认空港) { var lastAirportLeft = 默认空港; var car = { 司机: { startAccessPlaneInfo: 函数() { setInterval(函数() { console.log(“最后空港是“ + lastAirportLeft); }, 2000); } }; car.driver.startAccessPlaneInfo(); return { leaveTheAirport: 函数(airPortName) {
因为所有这些外部变量,由一个经文所指的函数,实际上是其经文所关闭的函数链中的本地变量(全球变量可以假设是某种根函数的本地变量),并且每个函数的单一执行都会产生其本地变量的新例子,因此,每个函数的执行都会返回(或以其他方式转换)。
此外,必须明白,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();