일반적으로는 자신의 스코프에 없는 것들에는 접근할 수 없습니다. 함수를 정의해 클로저를 만
들면 접근할 수 없었던 것들에 접근할 방법이 생깁니다. 이건 매우 중요한 측면입니다. 이후 장
에서 다시 설명하겠습니다.
7.7
즉시 호출하는 함수 표현식
6
장에서 함수 표현식에 대해 설명했습니다. 함수 표현식을 사용하면
즉시 호출하는 함수 표현
식
(
IIFE
)이란 것을 만들 수 있습니다.
IIFE
는 함수를 선언하고 즉시 실행합니다. 스코프와 클
로저에 대해 충분히 이해했으니 왜
IIFE
를 사용해야 하는지 이해할 수 있을 겁니다.
IIFE
는 다
음과 같은 형태를 취합니다.
(
function
() {
//
IIFE
바디
})();
함수 표현식으로 익명 함수를 만들고 그 함수를 즉시 호출합니다.
IIFE
의 장점은 내부에 있는
것들이 모두 자신만의 스코프를 가지지만,
IIFE
자체는 함수이므로 그 스코프 밖으로 무언가를
내보낼 수 있다는 겁니다.
const
message
= (
function
() {
const
secret
= "
I
'
m
a
secret
!";
return
`
The
secret
is
${
secret
.
length
}
characters
long
.`;
})();
console
.
log
(
message
);
변수
secret
은
IIFE
의 스코프 안에서 안전하게 보호되며 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month, and much more.
O’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
I wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
I’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
I'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.