js closure ,copy from stackoverflow
function foo(x) {
var tmp = 3;
function bar(y) {
alert(x + y + (++tmp)); // will alert 16
}
bar(10);
}
foo(2);
This will always alert 16, because
bar
can access the x
which was defined as an argument to foo
, and it can also access tmp
from foo
. That is a closure. A function doesn't have to return in order to be called a closure. Simply accessing variables outside of your immediate lexical scope creates a closure.
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + (++tmp)); // will also alert 16
}
}
var bar = foo(2); // bar is now a closure.
bar(10);
The above function will also alert 16, because
bar
can still refer to x
and tmp
, even though it is no longer directly inside the scope. However, since
tmp
is still hanging around inside bar
's closure, it is also being incremented. It will be incremented each time you call bar
. The simplest example of a closure is this:
var a = 10;
function test() {
console.log(a); // will output 10
console.log(b); // will output 6
}
var b = 6;
test();
When a JavaScript function is invoked, a new execution context is created. Together with the function arguments and the parent object, this execution context also receives all the variables declared outside of it (in the above example, both 'a' and 'b').
It is possible to create more than one closure function, either by returning a list of them or by setting them to global variables. All of these will refer to the same
x
and the same tmp
, they don't make their own copies. Here the number
x
is a literal number. As with other literals in JavaScript, when foo
is called, the number x
is copied into foo
as its argument x
. On the other hand, JavaScript always uses references when dealing with objects. If say, you called
foo
with an object, the closure it returns will reference that original object! function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + tmp);
x.memb = x.memb ? x.memb + 1 : 1;
alert(x.memb);
}
}
var age = new Number(2);
var bar = foo(age); // bar is now a closure referencing age.
bar(10);
As expected, each call to
bar(10)
will increment x.memb
. What might not be expected, is that x
is simply referring to the same object as the age
variable! After a couple of calls to bar
, age.memb
will be 2! This referencing is the basis for memory leaks with HTML objects.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[2022.04.19] 자바스크립트 this - 생성자 함수와 이벤트리스너에서의 this18일에 this에 대해 공부하면서 적었던 일반적인 함수나 객체에서의 this가 아닌 오늘은 이벤트리스너와 생성자 함수 안에서의 this를 살펴보기로 했다. new 키워드를 붙여 함수를 생성자로 사용할 때 this는...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.