자바스크립트에서 클로저(Closure)는 특정 함수가 자신이 선언될 당시의 환경(lexical environment)을 기억하는 현상을 말합니다.
클로저는 내부 함수가 외부 함수의 스코프에 있는 변수에 접근할 수 있게 하며, 외부 함수가 실행을 마친 후에도 그 변수를 기억합니다.
핵심 포인트는 다음과 같습니다:
- 함수 내의 함수: 클로저는 일반적으로 내부 함수가 외부 함수의 변수에 접근할 때 생성됩니다. 내부 함수는 외부 함수의 지역 변수에 접근할 수 있습니다.
- 변수의 지속성: 외부 함수가 실행을 마치고 반환되더라도, 내부 함수는 외부 함수의 변수에 대한 참조를 유지합니다. 이는 내부 함수가 호출될 때마다 해당 변수들이 여전히 사용 가능하다는 것을 의미합니다.
- 데이터 은닉과 캡슐화: 클로저를 사용하면 다른 코드로부터 변수를 보호하고 숨길 수 있습니다. 이는 자바스크립트에서 데이터를 캡슐화하고 정보를 숨기는 방법으로 사용될 수 있습니다.
클로저 = 함수와 그 함수가 선언된 렉시컬 환경의 조합
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.
In JavaScript, closures are created every time a function is created, at function creation time.
[1] Lexcial Scoping
The word lexical refers to the fact that lexical scoping uses the location where a variable is declared within the source code to determine where that variable is available (=> 범위를 결정함에 있어서 해당 변수가 "선언"된 곳이 중요함). Nested functions have access to variables declared in their outer scope.
[2] Scoping with let and const
Traditionally (before ES6), JavaScript only had two kinds of scopes: function scope and global scope.
Variables declared with var are either function-scoped or global-scoped, depending on whether they are declared within a function or outside a function.
This can be tricky, because blocks with curly braces do not create scopes:
if (Math.random() > 0.5) {
var x = 1;
} else {
var x = 2;
}
console.log(x);
For people from other languages (e.g. C, Java) where blocks create scopes, the above code should throw an error on the console.log line, because we are outside the scope of x in either block. However, because blocks don't create scopes for var, the var statements here actually create a global variable. => 헉스.. 나도 {}가 scope을 만드니 저 콘솔로그가 에러나야한다고 생각하고있었음...
In ES6, JavaScript introduced the let and const declarations, which allow you to create block-scoped variables.
=> 아하... 지금까지 현업에서 let 하고 const 만 쓰고 var을 안썼어서 위와 같은 이슈를 피할 수 있었나보다,,,,
if (Math.random() > 0.5) {
const x = 1;
} else {
const x = 2;
}
console.log(x); // ReferenceError: x is not defined
In essence, blocks are finally treated as scopes in ES6, but only if you declare variables with let or const.
[3] Closure
function makeFunc() {
const name = "Mozilla";
function displayName() {
console.log(name);
}
return displayName;
}
const myFunc = makeFunc();
myFunc();
A closure is the combination of a function and the lexical environment within which that function was declared. This environment consists of any local variables that were in-scope at the time the closure was created. In this case, myFunc is a reference to the instance of the function displayName that is created when makeFunc is run. The instance of displayName maintains a reference to its lexical environment, within which the variable name exists. For this reason, when myFunc is invoked, the variable name remains available for use, and "Mozilla" is passed to console.log.
Here's a slightly more interesting example—a makeAdder function:
function makeAdder(x) {
return function (y) {
return x + y;
};
}
const add5 = makeAdder(5);
const add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
In this example, we have defined a function makeAdder(x), that takes a single argument x, and returns a new function. The function it returns takes a single argument y, and returns the sum of x and y.
add5 and add10 both form closures. They share the same function body definition, but store different lexical environments. In add5's lexical environment, x is 5, while in the lexical environment for add10, x is 10.
[4] Practical Closures
Closures are useful because they let you associate data (the lexical environment) with a function that operates on that data.
... WIP ...
참고자료
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Closures - JavaScript | MDN
A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closur
developer.mozilla.org
'프론트엔드 > [언어] 자바스크립트' 카테고리의 다른 글
[Lexical Scope] Static Scoping vs. Dynamic scoping (0) | 2024.03.05 |
---|---|
자바스크립트의 객체참조모델과 가비지콜렉션 (1) | 2024.02.27 |
Single Thread (0) | 2024.02.27 |
자바스크립트에서 == 와 === 의 차이? (0) | 2024.02.26 |
코어 자바스크립트 [1] - 데이터 타입 (0) | 2024.02.26 |
댓글