如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
关闭是当内部函数以某种方式为外部函数以外的任何范围提供时创建的。
例子:
var outer = function(params){ //Outer function defines a variable called params
var inner = function(){ // Inner function has access to the params variable of the outer function
return params;
}
return inner; //Return inner function exposing it to outer scope
},
myFunc = outer("myParams");
myFunc(); //Returns "myParams"
其他回答
关闭是通过内部函数可以提到在其外部关闭函数中存在的变量,其母函数已经结束后。
// A function that generates a new function for adding numbers.
function addGenerator( num ) {
// Return a simple function for adding two numbers
// with the first number borrowed from the generator
return function( toAdd ) {
return num + toAdd
};
}
// addFive now contains a function that takes one argument,
// adds five to it, and returns the resulting number.
var addFive = addGenerator( 5 );
// We can see here that the result of the addFive function is 9,
// when passed an argument of 4.
alert( addFive( 4 ) == 9 );
下面是我最能给出的Zen答案:
你会期望这个代码做什么?在你运行它之前,在评论中告诉我!我很好奇!
function foo() {
var i = 1;
return function() {
console.log(i++);
}
}
var bar = foo();
bar();
bar();
bar();
var baz = foo();
baz();
baz();
baz();
现在,在您的浏览器中打开控制台(Ctrl + Shift + I 或 F12,希望)并插入代码并点击 Enter。
如果这个代码打印了你所期望的(JavaScript的新闻 - 忽略“未定义”的结尾),那么你已经有无语的理解。
我把它这样做,因为一旦我意识到这个代码将Foo()的内部函数的例子放在字符串和字符串中,然后通过这些变量呼叫它们,没有别的东西让我感到惊讶。
但如果我错了,并且控制台的输出让你惊讶,让我知道!
“关闭”这个词只是指能够在一个函数(六年:盒子)内访问关闭的物体(六年:物体)。即使函数(六年:盒子)不适用(六年:发送远程)。
维基百科 关闭:
在计算机科学中,关闭是一种函数,以及该函数的非本地名称(自由变量)的参考环境。
技术上,在JavaScript中,每个功能都是一个关闭,它总是有在周围范围内定义的变量访问。
由于JavaScript的范围定义结构是一种功能,而不是像许多其他语言一样的代码区块,我们通常在JavaScript中关闭的意思是与已执行的周围功能中定义的非本地变量的功能。
密封经常用来创建一些隐藏的私人数据的功能(但这并不总是如此)。
var db = (function() {
// Create a hidden object, which will hold the data
// it's inaccessible from the outside.
var data = {};
// Make a function, which will provide some access to the data.
return function(key, val) {
if (val === undefined) { return data[key] } // Get
else { return data[key] = val } // Set
}
// We are calling the anonymous surrounding function,
// returning the above inner function, which is a closure.
})();
db('x') // -> undefined
db('x', 1) // Set x to 1
db('x') // -> 1
// It's impossible to access the data object itself.
// We are able to get or set individual it.
EMS
上面的例子是使用一个匿名函数,一次执行,但它不一定是. 它可以被命名(例如 mkdb)并后续执行,每次被召唤时产生一个数据库函数. 每一个所产生的函数都会有自己的隐藏的数据库对象. 另一个使用例子关闭是当我们不返回一个函数时,但包含多个函数的对象
你和你的家人住在神话般的Ann Ville城,你有一个朋友住在门旁,所以你打电话给他们,请他们出去玩。
000001(JamiesHouse)
一个月后,你和你的家人从Ann Ville出发到下一个城市,但你和你的朋友仍然保持联系,所以现在你必须对你的朋友居住的城市的区域代码说话,然后说话他们的“正确”号码:
001 000001 (annVille.jamiesHouse)
01 001 000001 (myOldCountry.annVille.jamiesHouse)
事实上,如此可怕,你告诉你从你的老国家的杰米......你有一个好笑话,所以有一天,你和你的家人去度假回到老国家,你去参观你的老城(安·维尔),去参观杰米。
“真的?另一个杰米?在安·维尔?在你的新国家!!!?”“是的......让我们叫他们......”
观点?