Prototype JavaScript Closures for Dummies

황제낙엽 2009.04.08 09:46 조회 수 : 227 추천: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.

번호 제목 글쓴이 날짜 조회 수
117 Defining classes and inheritance (클래스 정의와 상속) 황제낙엽 2011.03.24 392
116 User Agent 관련 Reference URL 황제낙엽 2011.02.22 41
115 각 브라우저 별 User Agent 정보 황제낙엽 2011.02.22 823
114 History of User Agent 황제낙엽 2011.02.22 38
113 Navigator 객체란? 황제낙엽 2011.02.22 53
112 Understanding User-Agent Strings 황제낙엽 2011.02.22 76
111 User Agent 정보 모음 file 황제낙엽 2011.02.22 7768
110 ActiveX 설치 여부를 검사하는 스크립트 황제낙엽 2011.02.13 4053
109 [JavaScript Tutorials] Error handling in JavaScript using try/catch/finally - The Error object and throwing your own errors (해석중) 황제낙엽 2009.04.10 82
108 [JavaScript Tutorials] More leakage patterns (해석중) 황제낙엽 2009.04.10 142
107 [JavaScript Tutorials] Introducing the closure (해석중) 황제낙엽 2009.04.10 555
106 [JavaScript Tutorials] JavaScript and memory leaks (해석중) 황제낙엽 2009.04.08 102
105 [JavaScript Tutorials] Handling runtime errors in JavaScript using try/catch/finally (해석중) 황제낙엽 2009.04.08 2784
» JavaScript Closures for Dummies 황제낙엽 2009.04.08 227
103 자바스크립트 예약어 황제낙엽 2010.11.03 35
102 YUI Logger(Yahoo) 를 동적으로 로드하는 북마크릿 황제낙엽 2010.10.03 25
101 Javascript 를 사용하여 Binary File 읽기 황제낙엽 2010.09.29 499
100 크로스 브라우저를 위한 브라우저 검사 코드 file 황제낙엽 2010.08.27 86
99 Dynatrace For Ajax Performance 황제낙엽 2010.08.18 45
98 javascirpt IME-Mode 설정하기 황제낙엽 2010.08.17 1112