如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
如何向某人解释JavaScript关闭,知道它们所构成的概念(例如功能、变量等),但不了解关闭本身?
我已经在维基百科上看到了图表的例子,但不幸的是,它没有帮助。
当前回答
关闭是通过内部函数可以提到在其外部关闭函数中存在的变量,其母函数已经结束后。
// 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 );
其他回答
考虑到这个问题是关于简单地解释它,就像一个6岁的,我的答案是:
“当您在JavaScript中宣布函数时,它将永久地访问在该函数声明之前线上可用的所有变量和函数,该函数和它所访问的所有外部变量和函数都是我们称之为关闭的。
我不明白为什么这里的答案如此复杂。
下面是关闭:
var a = 42;
function b() { return a; }
是的,你可能每天使用它很多次。
没有理由相信关闭是一个复杂的设计黑客来解决具体问题. 不,关闭只是使用一个变量,从一个更高的范围从功能被宣布的观点(不运行)。 现在它允许你做什么可以更有观点,看看其他答案。
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 showName(firstName, lastName) {
var nameIntro = "Your name is ";
// this inner function has access to the outer function's variables, including the parameter
function makeFullName() {
return nameIntro + firstName + " " + lastName;
}
return makeFullName();
}
console.log(showName("Michael", "Jackson")); // Your name is Michael Jackson
此外,这是一个经典的关闭方式在jQuery,每个JavaScript和jQuery开发人员使用它很多:
$(function() {
var selections = [];
$(".niners").click(function() { // this closure has access to the selections variable
selections.push(this.prop("name")); // update the selections variable in the outer function's scope
});
});
实用关闭
//javascript function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; } var size12 = makeSizer(12); var size14 = makeSizer(14); var size16 = makeSizer(16); document.getElementById('size-12').onclick = size12; document.getElementById('size-14').onclick = size14; document.getElementById('size-16').onclick = size16; /*css*/ body {字体
我喜欢Kyle Simpson的关闭定义:
关闭是函数能够记住和访问其语法范围,即使该函数在其语法范围之外运行。
语法范围是当一个内部范围能够访问其外部范围时。
此分類上一篇: You Don't Know JS: Scopes & Closures
function foo() {
var a = 2;
function bar() {
console.log( a );
}
return bar;
}
function test() {
var bz = foo();
bz();
}
// prints 2. Here function bar referred by var bz is outside
// its lexical scope but it can still access it
test();