달력

3

« 2024/3 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
원래는 책에서 Closure에 대한 설명에 대한 설명이 있는데, 나의 관심을 끈 것은 Anonymous함수의 사용에 대한 것이었다.

아래의 예제는 동일한 동작을 하는 메소드를 Event에 추가하는 예제인데, 중간 정도에 보면 난데 없이 "(function(){" 으로 시작하는 구문이 나온다. 이 부분이 Anonymoun function 이다.
이렇게 만들면 "Global"로 선언할 필요없이 임시적으로 함수 블럭의 사용이 가능하다.
구문을 닫을 경우는 "})();"를 이용하면 된다.

 // An element with an ID of main
var obj = document.getElementById("main");

// An array of items to bind to
var items = [ "click", "keypress" ];

// Iterate through each of the items
for ( var i = 0; i < items.length; i++ ) {
    // Use a self-executed anonymous function to induce scope
    (function(){
        // Remember the value within this scope
        var item = items[i];
        // Bind a function to the elment
        obj[ "on" + item ] = function() {
            // item refers to a parent variable that has been successfully
            // scoped within the context of this for loop
            alert( "Thanks for your " + item );
        };
    })();
}

사실 위의 코드는 불필요한 내용들이 많이 들어있다. 굳지 저렇게 써야하나 라는 생각이 들지도 모르지만, 이것은 단지 예제 정도록 사용하면 된다.
그래도 몇가지 건질 것이 있다면, 위의 코드에서 "id"를 이용하여 오브젝트를 가져오고, Event를 Bind하는 내용을 담고 있는데, Event명을 obj["on" + item]의 형태로 Event를 binding한다.
위의 코드는 "click" 과 "keypress"에 대한 이벤트가 발생하면 메시지를 발생시키는 예제이다.

:
Posted by 행복상자