Node.js 공부기록 (4) closure
<JavaScript 기초 이론 다지기> closure
closure = function + environment
(클로져란, 함수와 환경의 합이다.)
closure는 function 이 하나 생길 때마나 하나씩 생깁니다.
environment 는 함수 자신을 둘러싼, 접근할 수 있는 모든 스코프를 뜻합니다.
Closure 예시
function and(x) {
return function print(y) {
return x + ‘ and ‘ + y
}
}
const saltAnd = and(‘salt’)
console.log(saltAnd(‘pepper’)) // salt and papper
console.log(saltAnd(‘sugar’)) // salt and sugar
and 함수로 만들어진 saltAnd의 closure는:
함수: print
환경: x => “salt”
and 함수는 higher-order function 이다. (고차원 함수, 고차함수)
closure는 higher-order function을 만드는 데 유용하다.
const waterAnd = and(‘water’)
console.log(waterAnd(‘juice’)) // water and juice
saltAnd와 waterAnd는 모두 함수는 같은 print이지만, 각각 주어진 변수가 다르다.
saltAnd는 x가 “salt”, waterAnd는 x가 “water”로 바인딩 되어 있다.
즉, 둘은 서로 다른 closure를 형성하고 있다.
function foo() {
function bar() {
}
function baz() {
}
}
foo()
이 코드의 실행과정에서 closure는 총 몇 개가 생겼을까?
정답은 3개 (foo 1개, bar 1개, baz 1개)
function foo() {
function bar() {
}
function baz() {
}
}
foo()
foo()
이 코드의 실행과정에서 closure는 총 몇 개가 생겼을까?
정답은 5개 (foo 1개, bar 2개, baz 2개)
function getCounter() {
var result = {
count: count,
total: 0
}
function count() {
result.total += 1
}
return result
}
var counter = getCounter()
counter.count()
counter.count()
console.log(counter.total)
실행결과는 2가 나온다.
function getCounter() {
var result = {
count: count,
total: 0
}
function count() {
result.total += 1
}
return result
}
var counterA = getCounter()
counterA.count()
counterA.count()
var counterB = getCounter()
counterB.count()
console.log(counterA.total, counterB.total)
실행결과는 2 1 이다.
counterA : 첫 getCounter 실행 때 만들어진 total과 count로 이루어진 객체
counterB: 두번째 getCounter 실행 때 만들어진 total과 count로 이루어진 객체
var numCounters = 0
function getCounter() {
numCounters += 1
var result = {
count: count,
total: 0
}
function count() {
result.total += 1
}
return result
}
var counterA = getCounter()
counterA.count()
counterA.count()
var counterB = getCounter()
counterB.count()
console.log(counterA.total, counterB.total, numCounters)
실행결과는 2 1 2 이다.
* node 디버거 활용하기
1. vscode 실행
2. .vscode 하위에 launch.json 파일 생성
3. 우측 하단의 [구성 추가…]([Add Configurations…]) 버튼 클릭
4. 이어서 [Node.js : Launch via npm] 항목 클릭
5. 아래처럼 내용 추가됨
{
“configurations”: [
{
“name”: “Launch via NPM”,
“request”: “launch”,
“runtimeArgs”: [
“run-script”,
“debug”
],
“runtimeExecutable”: “npm”,
“skipFiles”: [
“<node_internals>/**”
],
“type”: “pwa-node”
}
]
}
package.json 파일로 가서, 상단에
“scripts” : {
“debug”:”node src/main.js”
},
추가하기
ex)
{
“scripts”: {
“debug”:”node src/main.js”
}
}
src 폴더 하위에 main.js 파일 추가 및 내용 수정하기
/* eslint-disable */
var numCounters = 0
function getCounter() {
numCounters += 1
var result = {
count: count,
total: 0,
}
function count() {
result.total += 1
}
return result
}
var counterA = getCounter()
counterA.count()
counterA.count()
var counterB = getCounter()
counterB.count()
console.log(counterA.total, counterB.total, numCounters)
F5 키 누르면 디버그 시작