Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Scope example of a inner function
- var global_variable = 5;
- function simplefunc() {
- var local_variable = 6;
- function innerfunc() {
- console.log(global_variable);
- console.log(local_variable);
- }
- return innerfunc;
- }
- var f = simplefunc(); // innerfunc가 리턴됨
- f(); // prints '5', '6'
- // Q: '5' 는 알겠는데 '6'은? 어디서 튀어나왔지?
- // var local_variable은 지역변수에 불과한 것 아니었나?
- // A: simplefunc내에서 정의된 var local_variable은 innerfunc의 입장에서 보면
- // 전역 변수처럼 자신의 scope에서 접근이 가능하도록 innerfunc가
- // (자신의 'closure'에) 이 변수의 레퍼런스를 복사해간다.
- // 이 때문에 local_variable 변수의 lifespan은 계속 이어지게 된다.
Add Comment
Please, Sign In to add comment