如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
我不明白为什么这里的答案如此复杂。
下面是关闭:
var a = 42;
function b() { return a; }
是的,你可能每天使用它很多次。
没有理由相信关闭是一个复杂的设计黑客来解决具体问题. 不,关闭只是使用一个变量,从一个更高的范围从功能被宣布的观点(不运行)。 现在它允许你做什么可以更有观点,看看其他答案。
其他回答
好吧,和一个6岁的孩子谈话,我可能会使用随后的协会。
想象一下 - 你正在玩你的小兄弟姐妹在整个房子,你正在移动周围与你的玩具,并将其中的一些带到你的哥哥的房间。 过了一会儿,你的哥哥从学校回来,去了他的房间,他锁在里面,所以现在你不能访问玩具留在那里再直接的方式。
比较一个情况,当一个门被草案锁定,没有人在里面(通用功能执行),然后一些当地的火灾发生并燃烧房间(垃圾收集器:D),然后一个新的房间被建造,现在你可以留下其他玩具在那里(新功能例子),但从来没有得到相同的玩具留在第一间房间例子。
对于一个先进的孩子,我会把这样的东西放在下面,这不是完美的,但它让你感觉到它是什么:
function playingInBrothersRoom (withToys) {
// We closure toys which we played in the brother's room. When he come back and lock the door
// your brother is supposed to be into the outer [[scope]] object now. Thanks god you could communicate with him.
var closureToys = withToys || [],
returnToy, countIt, toy; // Just another closure helpers, for brother's inner use.
var brotherGivesToyBack = function (toy) {
// New request. There is not yet closureToys on brother's hand yet. Give him a time.
returnToy = null;
if (toy && closureToys.length > 0) { // If we ask for a specific toy, the brother is going to search for it.
for ( countIt = closureToys.length; countIt; countIt--) {
if (closureToys[countIt - 1] == toy) {
returnToy = 'Take your ' + closureToys.splice(countIt - 1, 1) + ', little boy!';
break;
}
}
returnToy = returnToy || 'Hey, I could not find any ' + toy + ' here. Look for it in another room.';
}
else if (closureToys.length > 0) { // Otherwise, just give back everything he has in the room.
returnToy = 'Behold! ' + closureToys.join(', ') + '.';
closureToys = [];
}
else {
returnToy = 'Hey, lil shrimp, I gave you everything!';
}
console.log(returnToy);
}
return brotherGivesToyBack;
}
// You are playing in the house, including the brother's room.
var toys = ['teddybear', 'car', 'jumpingrope'],
askBrotherForClosuredToy = playingInBrothersRoom(toys);
// The door is locked, and the brother came from the school. You could not cheat and take it out directly.
console.log(askBrotherForClosuredToy.closureToys); // Undefined
// But you could ask your brother politely, to give it back.
askBrotherForClosuredToy('teddybear'); // Hooray, here it is, teddybear
askBrotherForClosuredToy('ball'); // The brother would not be able to find it.
askBrotherForClosuredToy(); // The brother gives you all the rest
askBrotherForClosuredToy(); // Nothing left in there
正如你可以看到的那样,房间里留下的玩具仍然可以通过兄弟访问,不管房间是否被锁定。
在模块模式中,您定义了一个函数,然后立即在所谓的即时启动函数表达(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();
希望能帮忙......看,
关闭是一种功能,即使关闭了父母功能后,也可以访问父母范围。
var add = (function() {
var counter = 0;
return function() {
return counter += 1;
}
})();
add();
add();
add();
// The counter is now 3
例子解释:
变量添加被指定为自我召唤函数的回报值. 自我召唤函数只运行一次. 它将计算器设置为零(0),并返回函数表达式. 这种方式添加变成函数. “奇妙”部分是它可以在母范围内访问计算器. 这被称为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
能否向五岁男孩解释关闭?
我仍然认为谷歌的解释工作得很好,简要:
/*
* 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#问题