如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
好吧,和一个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
正如你可以看到的那样,房间里留下的玩具仍然可以通过兄弟访问,不管房间是否被锁定。
其他回答
我思考关闭的越多,我会看到它作为一个2步过程: init - 行动
init: pass first what's needed...
action: in order to achieve something for later execution.
到6岁时,我会强调关闭的实际方面:
Daddy: Listen. Could you bring mum some milk (2).
Tom: No problem.
Daddy: Take a look at the map that Daddy has just made: mum is there and daddy is here.
Daddy: But get ready first. And bring the map with you (1), it may come in handy
Daddy: Then off you go (3). Ok?
Tom: A piece of cake!
例如:把一些牛奶带到妈妈(=行动)。首先做好准备,然后把地图(=init)带到这里。
function getReady(map) {
var cleverBoy = 'I examine the ' + map;
return function(what, who) {
return 'I bring ' + what + ' to ' + who + 'because + ' cleverBoy; //I can access the map
}
}
var offYouGo = getReady('daddy-map');
offYouGo('milk', 'mum');
因为如果你带着一个非常重要的信息(地图),你有足够的知识来执行其他类似的操作:
offYouGo('potatoes', 'great mum');
对于一个开发人员来说,我会在关闭和OOP之间进行平行。 init 阶段类似于在传统 OO 语言中向构建者传达论点; 行动阶段最终是你呼吁实现你想要的方法。
请参见我的另一个答案,描述OO和关闭之间的平行性:
如何在JavaScript中“正确”创建自定义对象?
考虑到以下功能
function person(name, age){
var name = name;
var age = age;
function introduce(){
alert("My name is "+name+", and I'm "+age);
}
return introduce;
}
var a = person("Jack",12);
var b = person("Matt",14);
每次函数人被称为一个新的关闭创建,而变量 a 和 b 具有相同的输入函数,它与不同的关闭有关,而这个关闭仍然存在,即使函数人完成执行后。
此分類上一篇
a(); //My name is Jack, and I'm 12
b(); //My name is Matt, and I'm 14
一个抽象的封闭可以代表到这样的东西:
closure a = {
name: "Jack",
age: 12,
call: function introduce(){
alert("My name is "+name+", and I'm "+age);
}
}
closure b = {
name: "Matt",
age: 14,
call: function introduce(){
alert("My name is "+name+", and I'm "+age);
}
}
假设你知道一个班级在另一个语言是如何工作的,我会做一个类似。
想想像
JavaScript 作为构建器的本地变量作为例子属性这些属性是私人内部功能作为例子方法
每一天都有一个功能被称为
将创建一个包含所有本地变量的新对象,该对象的方法将访问该对象的“属性”。
函数 foo(x) { var tmp = 3;函数栏(y) { console.log(x + y + (++tmp)); // 会记录 16 } 栏(10); } foo(2);
函数栏,以及其与函数 foo 的语法环境的联系,是关闭。
函数 foo(x) { var tmp = 3; 返回函数 (y) { console.log(x + y + (++tmp)); // 还会记录 16 } } var bar = foo(2); bar(10); // 16 bar(10); // 17
一个关闭的最简单的例子是:
var a = 10; 函数测试() { console.log(a); // 将输出 10 console.log(b); // 将输出 6 } var b = 6; 测试();
下面的简单例子涵盖了JavaScript关闭的所有主要点。
下面是一家工厂,生产可以添加和复制的计算机:
function make_calculator() {
var n = 0; // this calculator stores a single number n
return {
add: function(a) {
n += a;
return n;
},
multiply: function(a) {
n *= a;
return n;
}
};
}
first_calculator = make_calculator();
second_calculator = make_calculator();
first_calculator.add(3); // returns 3
second_calculator.add(400); // returns 400
first_calculator.multiply(11); // returns 33
second_calculator.multiply(10); // returns 4000
关键点:每个呼叫做_计算机创建一个新的本地变量n,该计算机的添加和复制功能在做_计算机返回后很长时间仍然可用。
内部函数,如添加和加倍,其访问变量在外部函数中声明**,被称为关闭。
这是几乎所有的关闭。
此分類上一篇
* 例如,它涵盖了在另一个答案中提供的“关闭为Dummies”文章中的所有点,除了例子6,这简单地表明,变量可以在被宣布之前使用,这是一个很好的事实,但完全与关闭无关。
** 任何外部功能,如果有几种是无缝的,甚至在全球背景下,因为这个答案清楚地表明。
TLDR
细节
当一个函数通过内部(呼叫)方法引用时,函数对象的环境参考将复制到新创建的执行框架(stack frame)环境记录的外部环境参考。
在下面的例子中,函数f 关闭了全球执行背景的语法环境:
function f() {}
在下面的例子中,函数h在函数g的语法环境中关闭,而函数h则在全球执行背景的语法环境中关闭。
function g() {
function h() {}
}
如果内部函数由外部函数返回,则外部语法环境在外部函数返回后将继续存在,因为如果内部函数最终被召回,则外部语法环境必须可用。