클로저

이홍경·2022년 1월 4일
0
post-thumbnail

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.
참고 : MDN


MDN의 정의에 따르면 클로저는 묶인 함수 사이의 렉시컬환경의 조합이며, 내부 함수는 외부함수의 스코프에 접근할 수 있으며 함수가 생성될 때 마다 생성된다고 한다.

함수가 생성될때 내부 함수는 외부 렉시컬 환경을 참조하게 된다. 외부 함수의 스코프는 내부에서만 접근 및 수정 할 수 있게 되는 폐쇄적 관계를 형성하게 된다.


클로저 함수는

  • 외부함수는 함수를 반환해야함
  • 내부 함수는 외부 함수 스코프에 있는 식별자를 하나 이상 참조 해야한다.

ex)

const sum = x => y => x + y;
// 내부 함수가 외부 함수의 x값을 참조한다.
const sum = x => {
  return y => x + y
}
// 위와 같다
console.log(sum(3)(10)) // 13

왜 사용할까..⁉️

재사용성 👍

const add3 = sum(3);
console.log(add3(10)) // 13
console.log(add3(100)) // 103
------------------------------
const tagMaker = (tag) => (text) => `<${tag}><Text>${text}</Text></${tag}>`
const press = tagMaker('Pressable');
console.log(press('뒤로가기')) // <Pressable><Text>뒤로가기</Text></Pressable>
console.log(press('홈으로')) // <Pressable><Text>홈으로</Text></Pressable> 

전역변수를 줄이며 캡슐화

객체의 속성과 메서드를 하나로 묶고 실제 구현의 내용 일부를 외부에 감추어 은닉화 할 수 있다. 👍

마냥 좋기만 할까??

클로저를 사용한다는 것은 스코프체인으로 존재하는 변수객체가 남아있는 상태이기 때문에 자원을 많이

사용하고 성능이 좋지 않아진다고 한다.

profile
개발자를 꿈꾸는 자

0개의 댓글