如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
(我没有考虑到6年前的事情。
在JavaScript等语言中,您可以将函数作为参数转移到其他函数(函数是第一级公民的语言),您往往会发现自己正在做这样的事情:
var name = 'Rafael';
var sayName = function() {
console.log(name);
};
你可以看到, sayName 没有定义的名称变量,但它使用的名称值被定义在 sayName 之外(在母范围内)。
functionThatTakesACallback(sayName);
请注意:
接下来会发生什么? 参考错误:未定义的名称?
因此: 即使名称不在函数 sayName 将被召唤的范围内(函数ThatTakesACallback 内), sayName 可以访问与 sayName 相关的关闭中捕获的名称值。
───
其他回答
有些人非常接近得到简单的解释,然后变得复杂或保持抽象,击败目的,并无法显示一个非常简单的现实世界使用。
关闭有访问包含函数的变量 关闭在自己的内存空间中持久(因此对所有类型的 oop-y 实例物品都是有用的)
function sayHello(name) {
var text = 'Hello ' + name; // Local variable
console.log(text);
var sayAlert = function () {
alert(text);
}
return sayAlert;
}
sayHello();
/* This will write 'Hello undefined' to the console (in Chrome anyway),
but will not alert though since it returns a function handle to nothing).
Since no handle or reference is created, I imagine a good js engine would
destroy/dispose of the internal sayAlert function once it completes. */
// Create a handle/reference/instance of sayHello() using the name 'Bob'
sayHelloBob = sayHello('Bob');
sayHelloBob();
// Create another handle or reference to sayHello with a different name
sayHelloGerry = sayHello('Gerry');
sayHelloGerry();
/* Now calling them again demonstrates that each handle or reference contains its own
unique local variable memory space. They remain in memory 'forever'
(or until your computer/browser explode) */
sayHelloBob();
sayHelloGerry();
这表明了你应该关于关闭的两个基本概念。
在简单的说法中,我有一个基本函数,我可以创建参考或操作,其中包含独特的数据,留在记忆参考中。我不需要每次我想说别人的名字,我都需要重写函数。
认真对待这个问题,我们应该知道什么一个典型的6岁的人能够认知,但承认的是,一个对JavaScript感兴趣的人并不那么典型。
关于童年发展: 5 至 7 年,它说:
我们可以在JavaScript中编码此类内容:
函数 makeKitchen() { var trashBags = ['A', 'B', 'C']; // 只有 3 在第一次返回 { getTrashBag: 函数() { return trashBags.pop(); }; } var 厨房 = makeKitchen(); console.log(kitchen.getTrashBag()); // 返回垃圾袋 C console.log(kitchen.getTrashBag()); // 返回垃圾袋 B console.log(kitchen.getTrashBag()); // 返回垃圾袋 A
每次做Kitchen() 被召唤,一个新的关闭创建与自己的单独的废物Bags. 废物Bags 变量是本地到每个厨房的内部,并不能在外面访问,但内部功能在 getTrashBag 属性有访问它。
也许你应该考虑一个以对象为导向的结构而不是内部功能。
var calculate = {
number: 0,
init: function (num) {
this.number = num;
},
add: function (val) {
this.number += val;
},
rem: function (val) {
this.number -= val;
}
};
并从 calculate.number 变量中阅读结果,谁需要“返回”无论如何。
//Addition
First think about scope which defines what variable you have to access to (In Javascript);
//there are two kinds of scope
Global Scope which include variable declared outside function or curly brace
let globalVariable = "foo";
一件事要记住,一旦你宣布了一个全球变量,你可以在你的代码中的任何地方使用它,即使在功能中;
包含仅在您的代码的特定部分可用的变量的本地范围:
函数范围是当您在函数中宣布变量时,您只能在函数内访问变量。
function User(){
let name = "foo";
alert(name);
}
alert(name);//error
//Block scope is when you declare a variable within a block then you can access that variable only within a block
{
let user = "foo";
alert(user);
}
alert(user);
//Uncaught ReferenceError: user is not defined at.....
//A Closure
function User(fname){
return function(lname){
return fname + " " lname;
}
}
let names = User("foo");
alert(names("bar"));
//When you create a function within a function you've created a closure, in our example above since the outer function is returned the inner function got access to outer function's scope
JavaScript 的关闭与 scopes 的概念有关。
在 es6 之前,没有区块级范围,只有 JS 的功能级范围。
也就是说,每当需要区块级范围时,我们都需要将其插入一个函数中。
看看这个简单而有趣的例子,关闭如何解决这个问题在ES5
// 让我们说我们只能使用一个传统的路径,而不是forEach为(var i = 0; i < 10; i++) { setTimeout(函数() { console.log('没有关闭访问指数 - '+ i) }) ) } // 这将打印10次“访问指数 - 10”,这是不正确的 /** 预计输出是访问指数 - 0 访问指数 - 1.. 访问指数 - 9 **/ // 我们可以通过使用 cl 解决它
注:这可以轻松地通过使用 es6 取代 var 来解决,因为它创造了语法范围。
简而言之,在 JS 中关闭仅仅是访问功能范围。
关闭是函数内部的一个函数,它可以访问其“亲属”函数的变量和参数。
例子:
function showPostCard(Sender, Receiver) {
var PostCardMessage = " Happy Spring!!! Love, ";
function PreparePostCard() {
return "Dear " + Receiver + PostCardMessage + Sender;
}
return PreparePostCard();
}
showPostCard("Granny", "Olivia");