1 + 3
(1 + 3) + 4
[1,2]
// output 4, 7, (2) [1,2]
const a = 10; // 값으로 다룰 수 있으며 a라는 변수에 담을 수 있음.
const add10 = a => a + 10; // a는 함수의 인자로 사용되며, a + 10을 리턴함
const r = add10(a); // 함수도 일급 객체가 됨 (일급 함수)
const log = console.log;
const add5 = a => a + 5;
log(add5);
log(add5(5));
const f1 = () => () => 1;
log(f1());
const f2 = f1();
log(f2);
log(f2());
// output
a => a +5
15
() => 1
() => 1
1
const log = console.log;
const apply1 = f => f(1);
const add2 = a => a + 2;
log(apply1(add2)); // add2의 함수의 인자에 1이 들어감.
log(apply1(a => a - 1)); // 1 -1 => 0
const times = (f, n) => {
let i = -1;
while (++i < n) f(i);
};
times(log, 3); // console.log에 times안에 있는 i의 값이 찍힘 (0, 1, 2)
times(a => log(a + 10), 3);
// output
3
0
0
1
2
10
11
12
const log = console.log;
const addMaker = a => b => a + b;
const add10 = addMaker(10); // 외부 context : 10, 함수: b => a+ b
log(add10(5));
log(add10(10)); // addMaker에 있는 10에 접근하면서 클로저 사용
// output
15
20
클로저는 내부함수가 외부함수의 맥락(context)에 접근할 수 있는 것을 가르킨다. 클로저는 자바스크립트를 이용한 고난이도의 테크닉을 구사하는데 필수적인 개념으로 활용된다.
더 자세한 내용은 생활코딩 링크를 참조
https://opentutorials.org/course/743/6544