JS의 클로저
5978 단어 jsclosuresjavascriptfunctional
폐쇄란 무엇인가
먼저 JS에서 클로저가 무엇인지에 대해 조금 이야기해 봅시다. 다음은 (MDN)( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures )이 클로저를 정의하는 방법입니다.
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.
범위
클로저가 작동하는 방식을 이해하려면 JS의 범위를 잘 이해하고 있는지 확인하는 것이 좋습니다. 이는 어떤 컨텍스트에서 어떤 변수를 사용할 수 있는지 정의합니다. 전역 변수는 코드의 어느 곳에서나 사용할 수 있으며 함수 외부에서 생성되며 일반적으로 코드 시작 부분에서 생성됩니다. 로컬 변수(로컬 범위)는 함수 내에서 생성되며 해당 함수 내에서만 사용할 수 있습니다.
통사론
클로저는 기본적으로 중첩된 함수이며 내부 함수와 외부 함수가 있습니다. 아래 예에서 updateClicks
는 외부 함수이고 reportClicks
는 내부 함수입니다. 이것이 의미하는 바는 reportClicks
가 자체 범위 내에서 정의된 모든 함수뿐만 아니라 updateClicks
외부 함수에 정의된 모든 변수에 액세스할 수 있다는 것입니다. 여기에서 우리는 reportClicks()
를 호출하지 않고 단순히 반환하는 것이므로 나중에 액세스할 수 있습니다.
function updateClicks() {
let clicks = {};
function reportClicks(item) {
clicks[item] = clicks[item] + 1 || 1;
console.log(item, clicks);
}
return reportClicks();
}
클로저 내의 변수
클로저 내에서 정의된 변수는 다른 변수와 마찬가지로 업데이트 및 변경될 수 있습니다. 다른 예를 살펴보겠습니다. 아래 예에서는 충족된 기준에 따라 무엇meal
이 반환될지 결정하기 위해 in/else 문을 사용하고 있습니다.
function hungry(meal) {
function whatsForDinner() { // whatsForDinner() is an inner function, a closure
if (!meal) { // whatsForDinner() uses argument provided to the parent function
console.log('Is it time to eat?');
} else if (meal === 'Port Chops') {
console.log('These are my favorite');
} else {
console.log(`I'm eating ${meal} for dinner.`);
}
}
function digest() { // digest() is an inner function, a closure
meal = undefined; // digest() uses argument provided to the parent function
}
return {
whatsForDinner,
digest
};
}
요약
이것은 중첩 함수 또는 클로저가 JS에서 작동하는 방식에 대한 약간의 설명입니다. 특히 JS에 정통하지 않은 경우 클로저를 파악하기가 까다로울 수 있습니다. 그들과 함께 연습하고 다른 것과 마찬가지로 그들과 함께 작업하고 앱에서 구현할 수 있습니다!
자원
MDN
ECMA-262-3 in detail. Chapter 6. Closures
Reference
이 문제에 관하여(JS의 클로저), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/randysteele/closures-in-js-5hg8
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
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.
클로저가 작동하는 방식을 이해하려면 JS의 범위를 잘 이해하고 있는지 확인하는 것이 좋습니다. 이는 어떤 컨텍스트에서 어떤 변수를 사용할 수 있는지 정의합니다. 전역 변수는 코드의 어느 곳에서나 사용할 수 있으며 함수 외부에서 생성되며 일반적으로 코드 시작 부분에서 생성됩니다. 로컬 변수(로컬 범위)는 함수 내에서 생성되며 해당 함수 내에서만 사용할 수 있습니다.
통사론
클로저는 기본적으로 중첩된 함수이며 내부 함수와 외부 함수가 있습니다. 아래 예에서 updateClicks
는 외부 함수이고 reportClicks
는 내부 함수입니다. 이것이 의미하는 바는 reportClicks
가 자체 범위 내에서 정의된 모든 함수뿐만 아니라 updateClicks
외부 함수에 정의된 모든 변수에 액세스할 수 있다는 것입니다. 여기에서 우리는 reportClicks()
를 호출하지 않고 단순히 반환하는 것이므로 나중에 액세스할 수 있습니다.
function updateClicks() {
let clicks = {};
function reportClicks(item) {
clicks[item] = clicks[item] + 1 || 1;
console.log(item, clicks);
}
return reportClicks();
}
클로저 내의 변수
클로저 내에서 정의된 변수는 다른 변수와 마찬가지로 업데이트 및 변경될 수 있습니다. 다른 예를 살펴보겠습니다. 아래 예에서는 충족된 기준에 따라 무엇meal
이 반환될지 결정하기 위해 in/else 문을 사용하고 있습니다.
function hungry(meal) {
function whatsForDinner() { // whatsForDinner() is an inner function, a closure
if (!meal) { // whatsForDinner() uses argument provided to the parent function
console.log('Is it time to eat?');
} else if (meal === 'Port Chops') {
console.log('These are my favorite');
} else {
console.log(`I'm eating ${meal} for dinner.`);
}
}
function digest() { // digest() is an inner function, a closure
meal = undefined; // digest() uses argument provided to the parent function
}
return {
whatsForDinner,
digest
};
}
요약
이것은 중첩 함수 또는 클로저가 JS에서 작동하는 방식에 대한 약간의 설명입니다. 특히 JS에 정통하지 않은 경우 클로저를 파악하기가 까다로울 수 있습니다. 그들과 함께 연습하고 다른 것과 마찬가지로 그들과 함께 작업하고 앱에서 구현할 수 있습니다!
자원
MDN
ECMA-262-3 in detail. Chapter 6. Closures
Reference
이 문제에 관하여(JS의 클로저), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/randysteele/closures-in-js-5hg8
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
function updateClicks() {
let clicks = {};
function reportClicks(item) {
clicks[item] = clicks[item] + 1 || 1;
console.log(item, clicks);
}
return reportClicks();
}
클로저 내에서 정의된 변수는 다른 변수와 마찬가지로 업데이트 및 변경될 수 있습니다. 다른 예를 살펴보겠습니다. 아래 예에서는 충족된 기준에 따라 무엇
meal
이 반환될지 결정하기 위해 in/else 문을 사용하고 있습니다.function hungry(meal) {
function whatsForDinner() { // whatsForDinner() is an inner function, a closure
if (!meal) { // whatsForDinner() uses argument provided to the parent function
console.log('Is it time to eat?');
} else if (meal === 'Port Chops') {
console.log('These are my favorite');
} else {
console.log(`I'm eating ${meal} for dinner.`);
}
}
function digest() { // digest() is an inner function, a closure
meal = undefined; // digest() uses argument provided to the parent function
}
return {
whatsForDinner,
digest
};
}
요약
이것은 중첩 함수 또는 클로저가 JS에서 작동하는 방식에 대한 약간의 설명입니다. 특히 JS에 정통하지 않은 경우 클로저를 파악하기가 까다로울 수 있습니다. 그들과 함께 연습하고 다른 것과 마찬가지로 그들과 함께 작업하고 앱에서 구현할 수 있습니다!
자원
MDN
ECMA-262-3 in detail. Chapter 6. Closures
Reference
이 문제에 관하여(JS의 클로저), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/randysteele/closures-in-js-5hg8
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
MDN
ECMA-262-3 in detail. Chapter 6. Closures
Reference
이 문제에 관하여(JS의 클로저), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/randysteele/closures-in-js-5hg8텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)