블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2013. 1. 27. 20:10 Languages/JavaScript

this를 자바스크립트에서 만나게 되면 이게 어느 인스턴스의 this인지 파악하기가 난해하다. this는 context(Execute Context)와 Scope(유효범위)에 대한 부분을 잘 알아야 한다. 

 

1) function안에서 변수 접근 권한

function someFunc() {
    var _this = this;
    something.on("click", function() {
        console.log(_this);
    });
};

  - var _this = this; 문구는 왜 사용하는 것일까?

  - 첫번재 유효범위(First Scope)는 Global Scope 이다

    + 모든 변수(Variable)과 함수(Function)은 global이다. 

    + Global Scope는 window 객체이다 

    + window.x = 9; 라고 property를 설정하면 어디서나 접근이 가능하다 

 

function myFunc() {
    var x = 5;
});
console.log(x); // undefined

  - x 는 myFunc()안에서 초기화 되었고, myFunc()안에서만 접근이 가능하다 

  - var 키워드를 사용하지 않으면 자동으로 global 유효범위로 만들어진다 

  - var 키워드를 사용하면 function이 호출 될때 생성되는 context에 지역변수로(local variable) 포함된다

function myFunc() {
    x = 5;
});
console.log(x); // 5

 

  - Outer Function에 정의된 모든 변수는 다른 Inner Function에서 접근을 할 수 있다

function outer() {
   var x = 5;
   function inner() {
      console.log(x); // 5
   }
   inner();
}

 

  - Outer Function에서는 Inner Function의 변수를 접근 할 수 없다 

function outer() {
    var x = 5;
    function inner() {
        console.log(x); //5 
        var y = 10;
    }
    inner();
    console.log(y); //undefined
}

 

2) this의 유효범위 

  - this는 function이 호출될 때 자동으로 설정되는 변수이다 

  - 변수의 값은 function이 어떻게 호출되냐에 따라 틀려진다

  - 자바스크립트에서 함수를 호출하는 주된 몇가지 방법을 가지고 있다. (주로 사용하는 3가지 방법)

    + function이 method처럼 호출하기 : when a function is called as a method === 오브젝트.function은 메소드라 칭함

    + 자기자신위에 호출하기  : when a function is called on it's own === function 자체가 호출 오브젝트.function이 아닐 경우

    + event handler로서 호출하기 : when a function is called as an event handler == 이벤트 핸들러 수행시 호출되는 function

function foo() {
   console.log(this); //global object
};

myapp = {};
myapp.foo = function() {
   console.log(this); //points to myapp object
또는 (같은 내용)
myapp = {
   foo: function() {
     console.log(this); //points to myapp object
   }
}

var link = document.getElmentById("myId");
link.addEventListener("click", function() {
   console.log(this); //points to link
}, false);

  - addEventLister를 사용하여 function을 붙이면 this의 값이 변경된다 : this값은 caller로 부터 function에 전달된다 

 

 

$("myLink").on("click", function() {
    console.log(this); //points to myLink (as expected)
    var _this = this;  //store reference
    $.ajax({
        //ajax set up
        success: function() {
            console.log(this); //points to the global object. Huh?
            console.log(_this); //better!
        }
    });
});

  - myLink을 click하면 function이 수행된다. 이때 이벤트 핸들러로서 펑션의 this는 myLink DOM element의 참조로 설정된다

  - 그러나 ajax 정규호출의 this는 global object로 this 값을 설정한다. 이는 "event handler"도 "오브젝트 method"도 아닌 function이기 때문이다

  - 위와 같이 하는 것이 function을 호출하는 곳에서 this에 대한 값을 정확히 사용하기 위한 방법이다

 

 

3) Crockford on JavaScrpt

  - 백발의 중년 신사분이 JavaScript 언어에 대해 설명을 하고 있다. 우리나라에선 상상할 수 없는 일이겠지, 큰 세미나에 가봐야 젊은 친구들의 열정만을 엿볼 수 있는 부분을 생각해 보면 그들의 환경이 참 부럽다.

  - 15분경의 동영상에서 this의 호출에 대해서 보자 

  - 31분경에서 정확한 Closure 사용법 설명

 

 

<참조> 

  - 원문 : Scope and this in JavaScript

  - Scope 한글 블로깅 연재

  - Naver Dev JavaScript 클로져, 유효범위

posted by 윤영식