IT web/JavaScript

function 과 this

Pina Colada 2015. 12. 11. 10:53

자바스크립트에서는

function이 호출되는 방법에 따라

function scope에 있는 this에 바인딩 되는 객체가 다릅니다.


//1.Method Call Pattern (메소드 호출 패턴)
//함수를 객체의 property(속성)에 저장하는 경우
var myObject ={
    value: 0,
    increment : function (inc){
        //메소드를 호출할 때 this는 메소드를 포함하고 있는 개체에 바인딩
        console.log("method -> this : " + this);
        console.log("method -> this.value : " + this.value);
        this.value += typeof inc === 'number' ? inc : 1;
    }    
};

myObject.increment(2);

//2. function Call Pattern (함수 호출 패턴)
//함수가 객체의 속성이 아닌경우
//this에 window객체가 바인딩
function outerFunc(){
    console.log("outterFunc -> this : " + this);
    
    function innerFunc(){
        console.log("innerFunc -> this : " + this);
    }
    
    innerFunc();
}

outerFunc();

//3. Constructor Call Pattern (생성자 호출 패턴)
var Quo = function(string){
    this.status = string;  
};

Quo.prototype.get_status = function(){
    console.log("constructor -> this : " + this);
    console.log("constructor -> this.status : " + this.status);
    return this.status;
};

//함수를 new라는 전치 연산자와 함께 호출하면,
//호출한 함수의 prototype 속성의 값에 연결되는 (숨겨진)링크를 갖는 인스턴스객체가 생성되고,
//이 새로운 객체는 this에 바인딩 된다.
var myQuo = new Quo("confused");

console.log(myQuo.get_status());


//4. apply Call Pattern 
//(this를 직접 지정해서 바인딩)
var statusObject ={
    status: 'A-OK'
};

var status = Quo.prototype.get_status.apply(statusObject);


출처 : 더글라그 크락포드의 자바스크립트 핵심 가이드, 더글라스 크락포드 저, 김명신 역, 한빛미디어