JavaScript

[JS] 함수 호출패턴과 This 바인딩

앙꼬오빠 2018. 1. 27. 14:47

함수 호출패턴


외부함수는 window의 메서드가 된다.

내부함수 역시 this는 window를 가리키게 된다.


function kim() {

    console.log(this);    //window

    function wook() {

        console.log(this);    //window

    }

    wook();

}

    

kim();




객체 내의 this는 자신의 객체를 기리킨다.

하지만 객체 내의 메서드의 내부 함수(콜백 함수도 마찬가지)의 this는 자신의 객체가 아닌 window(전역객체)를 가리킨다.


var value = 1;

var commonctrl = {

    value : 100,

    web : function() {

        console.log('This ' + this);    //commonctrl

        console.log('This ' + this.value);    //100

        setTimeout(function() {

            console.log('This ' + this);    //window

            console.log('This ' + this.value);    //1

        }, 1000);

    }

};

commonctrl.web();



아래와 같은 방법으로 this가 전역객체를 참조하는 것을 회피할 수 있다.


var value = 1;

var commonctrl = {

    value : 100,

    web : function() {

        var that = this;    //commonctrl

        console.log('This ' + that);    //commonctrl

        console.log('This ' + that.value);    //100

        setTimeout(function() {

            console.log('This ' + that);    //commonctrl

            console.log('This ' + that.value);    //100

        }, 1000);

    }

};

commonctrl.web();