Created
September 19, 2011 11:36
-
-
Save rillflow/1226334 to your computer and use it in GitHub Desktop.
JavaScript closure stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function insertClosureStack(obj, name, variable) { | |
var old = obj[name]; | |
obj[name] = function (n) { | |
if ( typeof n == 'number' ) { // 인자가 있는 경우 검색 시작 | |
if ( variable == n ) { // 클로저 꼭대기 환경변수 variable 값과 주어진 인자를 비교 | |
console.log('found ' + variable); // 맞으면 출력 | |
} else { // 아니면 | |
if ( typeof old == 'function' ) { // 직전 환경을 갖고있는 클로저(function)가 정의되어 있는지 확인 후 | |
old(n); // 있으면 호출하며 양파껍질 하나를 벗김 | |
} else { // 없으면 양파속 끝(스택 바닥)까지 온거임 | |
console.log('Not found'); // 따라서 Not found | |
} | |
} | |
} else { // 인자가 없는 경우 | |
console.log(variable); // 비교과정 없이 바로 클로저 꼭대기 환경변수 variable 값 출력 | |
if ( typeof old == 'function' ) { // 위에있는 클로저 정의 확인과정과 동일 | |
old(n); | |
} | |
} | |
}; | |
}; | |
var stack = {}; | |
insertClosureStack(stack, 'print', '1'); // old가 undefined인 양파속 끝부분에 해당하는 최초 환경 정의 | |
insertClosureStack(stack, 'print', '2'); // old가 이전환경 저장하며 stack[print] 에는 새로운 클로져 정의 | |
insertClosureStack(stack, 'print', '3'); // 이제부터 무한반복 | |
insertClosureStack(stack, 'print', '4'); | |
insertClosureStack(stack, 'print', '5'); | |
insertClosureStack(stack, 'print', '6'); | |
insertClosureStack(stack, 'print', '7'); | |
// 스택에 포함된 특정값만 검색후 해당내용 출력할 경우 | |
stack.print(3); // 정상적으로 찾고 출력 | |
stack.print(10); // 없으면 Not found | |
// 인자없이 호출하면 스택 꼭대기부터 전부 출력 | |
stack.print(); | |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment