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.

번호 제목 글쓴이 날짜 조회 수
197 XMLHttpRequest.timeout 황제낙엽 2018.11.03 248
196 IFrames and cross-domain security file 황제낙엽 2012.01.13 246
195 UTF-8 한글 초성 추출 (자바스크립트) 황제낙엽 2019.05.07 243
194 Why does this simple Javascript prototype not work in IE? 황제낙엽 2011.03.24 242
193 Function.apply and Function.call in JavaScript 황제낙엽 2011.10.07 238
192 브라우저에서 뒤로 가기 막기와 펑션키(function key) 막기 황제낙엽 2005.10.21 236
191 두 서버의 자원을 접근하는 클라이언트 프레임웍(Next.js)에서의 CORS오류 file 황제낙엽 2021.12.05 231
» JavaScript Closures for Dummies 황제낙엽 2009.04.08 227
189 Javascript ArrayBuffer ? Binary handling in javascript 황제낙엽 2012.03.19 218
188 javascript array contains method 황제낙엽 2011.08.19 210
187 char to hex string 황제낙엽 2011.11.29 206
186 How to use Rhino to script Java classes. 황제낙엽 2008.07.14 198
185 Page Refresh/Reload 황제낙엽 2007.08.24 197
184 [펌] 아사페릴의 사생활 - Code Conventions for the JavaScript Programming Language 황제낙엽 2009.04.02 194
183 Reference Count (순환참조) 황제낙엽 2011.11.24 191
182 JavaScript Form Validation file 황제낙엽 2008.11.24 186
181 code compressor & decompressor 황제낙엽 2015.01.02 181
180 자바스크립트의 데이터 타입과 변수 황제낙엽 2008.08.06 179
179 SelectBox 밑에 CheckBox가 포함된 리스트 만들기 file 황제낙엽 2007.01.16 178
178 서비스 워커 file 황제낙엽 2020.05.25 177