Prototype JavaScript Closures for Dummies

황제낙엽 2009.04.08 09:46 조회 수 : 644 추천:122

sitelink1  
sitelink2  
sitelink3  
sitelink4 http://1 
extra_vars4 ko 
extra_vars5 http://blog.morrisjohns.com/javascript_closures_for_dummies 
extra_vars6 sitelink1 

JavaScript Closures for Dummies

begin content

 

  • a closure is the local variables for a function - kept alive after the function has returned, or
  • a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)
    클로져는 펑션이 리턴된 후 계속해서 펑션의 상태를 유지시키는 로컬 변수이다.
    클로져는 펑션이 리턴될 때 해제되지 않는 stack-frame 이다.

The following code returns a reference to a function:


function sayHello2(name) {
var text = 'Hello ' + name; // local variable
var sayAlert = function() { alert(text); }
return sayAlert;
}


Most JavaScript programmers will understand how a reference to a function is returned to a variable in the above code. If you don't, then you need to before you can learn closures. A C programmer would think of the function as returning a pointer to a function, and that the variables sayAlert and say2 were each a pointer to a function. 
대부분의 자바스크립트 프로그래머들은 코드상에서 variable로 리턴되는 펑션이 어떻게 레퍼런스 되는지 이해하고 있을 것이다. 만약 당신이 그런 사실을 모른다면 당신은 클로져를 배우기 전에 필요한 것이 있다. C프로그래머는 펑션에 대한 포인터를 리턴한다고 생각할 것이다. 그리고 "sayAlert" 과 "say2" 변수들이 각각 펑션의 포인터라고 여길것이다.

There is a critical difference between a C pointer to a function, and a JavaScript reference to a function. In JavaScript, you can think of a function reference variable as having both a pointer to a function as well as a hidden pointer to a closure.
C와 JavaScript 의 펑션 사이에는 중요한 차이점이 있다. 자바스크립트의 경우에는, 펑션에 대한 포인터 뿐만아니라 클로져에 대한 숨겨진 포인터 둘다를 가지는 펑션 레퍼런스 변수를 생각할 수 있다.


The above code has a closure because the anonymous function function() { alert(text); } is declared inside another function, sayHello2() in this example. In JavaScript, if you use the function keyword inside another function, you are creating a closure.
코드상에는 클로져가 있다. 예제에서 익명function (function() { alert(text); })는 또다른 function(sayHello2()) 내에 선언되어 있기 때문이다. 자바스크립에서는 만약 당신이 어떠한 function내에서 또다시 "function" 키워드를 사용하게 된다면 클로져를 생성하고 있다는 것을 의미한다.


In C, and most other common languages after a function returns, all the local variables are no longer accessable because the stack-frame is destroyed.
C를 포함하여 대부분의 다른 일반적인 랭귀지들은 펑션 리턴후에 모든 로컬 변수들은 더이상 접근할 수 없다. 왜냐하면 stack-frame 이 제거되기 때문이다.


In JavaScript, if you declare a function within another function, then the local variables can remain accessable after returning from the function you called. This is demonstrated above, because we call the function say2(); after we have returned from sayHello2(). Notice that the code that we call references the variable text, which was a local variable of the function sayHello2().
자바스크립트의 경우에는 만약 당신이 어떤 function을 또다른 function내에 선언한다면 로컬 변수들은 당신이 호출하여 function 리턴된 후에도 접근가능 상태를 유지할 수 있다. 이것은 그 이상을 의미하기도 한다. 왜냐하면 sayHello2() function을 리턴한 후에 우리는 say2(); function을 호출하기 때문이다. 코드는 우리가 function sayHello2()의 로컬 변수였던 variable text의 레퍼런스를 호출한다는 것을 알려준다.

function() {

alert(text);

}


Click the button above to get JavaScript to print out the code for the anonymous function. You can see that the code refers to the variable text. The anonymous function can reference text which holds the value 'Jane' because the local variables of sayHello2() are kept in a closure.

The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in - similar to how delegates are a method pointer plus a secret reference to an object.

번호 제목 글쓴이 날짜 조회 수
106 [JavaScript Tutorials] JavaScript and memory leaks (해석중) 황제낙엽 2009.04.08 443
105 [JavaScript Tutorials] Handling runtime errors in JavaScript using try/catch/finally (해석중) 황제낙엽 2009.04.08 3081
» JavaScript Closures for Dummies 황제낙엽 2009.04.08 644
103 자바스크립트 예약어 황제낙엽 2010.11.03 408
102 YUI Logger(Yahoo) 를 동적으로 로드하는 북마크릿 황제낙엽 2010.10.03 358
101 Javascript 를 사용하여 Binary File 읽기 황제낙엽 2010.09.29 794
100 크로스 브라우저를 위한 브라우저 검사 코드 file 황제낙엽 2010.08.27 461
99 Dynatrace For Ajax Performance 황제낙엽 2010.08.18 374
98 javascirpt IME-Mode 설정하기 황제낙엽 2010.08.17 1411
97 Iframe 내의 페이지 접근방법 황제낙엽 2009.11.12 400
96 외부 라이브러리 (.js) 의 바람직한 동적 로딩 (The best way to load external JavaScript) 황제낙엽 2009.10.05 636
95 숫자값으로의 변환 형태 황제낙엽 2009.09.02 413
94 Boolean 데이터 타입 황제낙엽 2009.09.02 436
93 toString 변환 테이블 황제낙엽 2009.09.02 402
92 URI 인코딩을 해야 하는 문자들 황제낙엽 2009.09.02 373
91 체인 생성자(생성자 체인), 프로토타입 체인 그리고 생성자 재지정 황제낙엽 2009.08.12 353
90 이미지 로드 코드 황제낙엽 2009.06.27 463
89 자동 형변환 (문자열 -> 숫자) 황제낙엽 2009.06.25 452
88 자바스크립트 쿠키 황제낙엽 2009.06.11 425
87 이클립스에 Aptana 플러그인 설치하기 (자바스크립트 개발에 유용한 IDE) 황제낙엽 2009.04.17 397