this 22

this 키워드

this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
(일반적으로 객체의 메서드 내부 또는 생성자 함수 내부에서만 의미가 있다.)
this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.

// 객체 리터럴
const circle = {
    radius:5,
    getDiameter(){
        // this는 메서드를 호출한 객체를 가리킨다.
        return 2 * this.radius;
    }
}
console.log(circle.getDiameter()); // 10
// 생성자 함수
function Circle(radius){
    // this는 생성자 함수가 생성할 인스턴스를 가리킨다.
    this.radius = radius;
}
Circle.prototype.getDiameter = function(){
    // this는 생성자 함수가 생성할 인스턴스를 가리킨다.
    return 2 * this.radius;
}
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10

함수 호출 방식과 this 바인딩

this 바인딩(this에 바인딩될 값)은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.

// this 바인딩은 함수 호출 방식에 따라 동적으로 결정된다.
const foo = function(){
    console.dir(this);
}

// 1. 일반 함수 호출
// foo 함수 내부의 this는 전역 객체 window를 가리킨다.
foo(); // window

// 2. 메서드 호출
// foo 함수를 프로퍼티 값으로 할당하여 호출
// foo 함수 내부의 this는 메서드를 호출한 객체 obj를 가리킨다.
const obj = { foo };
obj.foo(); // obj

// 3. 생성자 함수 호출
// foo 함수 내부의 this는 생성자 함수가 생성한 인스턴스를 가리킨다.
new foo(); // foo {}

// 4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출
// foo 함수 내부의 this는 인수에 의해 결정된다.
const bar = { name: 'bar' };
foo.call(bar); // bar
foo.apply(bar); // bar
foo.bind(bar); // bar

1. 일반 함수 호출

기본적으로 this에는 전역 객체가 바인딩된다.
strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩된다.

function foo(){
    'use strict';
    console.log(this); // undefined
}

cf. var 키워드로 선언한 전역 변수는 전역 객체의 프로퍼티지만, const 키워드로 선언한 전역 변수는 전역 객체의 프로퍼티가 아니다.
일반 함수로 호출된 모든 함수(중첩함수,콜백함수 포함) 내부의 this에는 전역 객체가 바인딩된다.
중첩 함수 또는 콜백 함수는 외부 함수를 돕는 헬퍼 함수의 역할을 하는데, 이 함수들의 this가 외부 함수 this와 일치 하지 않으면 문제가 생긴다.
메서드 내부의 중첩 함수나 콜백 함수의 this 바인딩을 메서드의 this 바인딩과 일치시키기 위한 방법은 다음과 같다.

var value = 1;
const obj = {
    value:100,
    foo(){
        // this 바인딩(obj)을 변수 that에 할당한다.
        const that = this;
        setTimeout(function(){
            console.log(that.value); // 100
        }, 100)
    }
};
obj.foo();

이 방법 외에도 자바스크립트는 this를 명시적으로 바인딩할 수 있는 Function.prototype.apply/call/bind 메서드를 제공한다.

var value = 1;
const obj = {
    value:100,
    foo(){
        // 콜백 함수에 명시적으로 this를 바인딩한다.
        setTimeout(function(){
            console.log(this.value); // 100
        }.bind(this), 100)
    }
};
obj.foo();

화살표 함수를 사용해서 this 바인딩을 일치시킬 수도 있다.

var value = 1;
const obj = {
    value:100,
    foo(){
        // 화살표 함수 내부의 this는 상위 스코프의 this를 가리킨다.
        setTimeout( () => console.log(this.value), 100); // 100        
    }
};
obj.foo();

2. 메서드 호출

메서드 내부의 this는 메서드를 호출한 객체에 바인딩된다.

3. 생성자 함수 호출

생성자 함수 내부의 this에는 생성자 함수가(미래에) 생성할 인스턴스가 바인딩된다.

4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출

apply/call

apply와 call 메서드의 본질적인 기능은 함수를 호출하는 것이다.
apply와 call 메서드는 함수를 호출하면서 첫 번째 인수로 전달한 특정 객체를 호출한 함수의 this에 바인딩한다.

function getThisBinding(){
    console.log(arguments);
    return this;
}
const thisArg = {a:1};
// apply 메서드는 호출할 함수의 인수를 배열로 묶어 전달한다.
console.log(getThisBinding.apply(thisArg, [1,2,3]));
// Arguments(3)
// {a:1}

// call 메서드는 호출할 함수의 인수를 쉼표로 구분한 리스트 형식으로 전달한다.
console.log(getThisBinding.call(thisArg, 1,2,3));
// Arguments(3)
// {a:1}
function convertArgsToArray(){
    return Array.prototype.slice.call(arguments);
}
convertArgsToArray(1,2,3); // [1,2,3]

bind

Function.prototype.bind 메서드는 apply와 call 메서드와 달리 함수를 호출하지 않고 this로 사용할 객체만 전달한다.

function getThisBinding(){
    return this;    
}
const thisArg = {a:1};
console.log(getThisBinding.bind(thisArg)); // getThisBinding
console.log(getThisBinding.bind(thisArg)()); // {a:1}

bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용된다.

const person = {
    name:'lee',
    foo(callback){
        setTimeout(callback.bind(this), 100);
    }
};
person.foo(function(){
    console.log(`${this.name}`); // 'lee'
});
함수 호출 방식 this 바인딩
일반 함수 호출 전역 객체
메서드 호출 메서드를 호출한 객체
생성자 함수 호출 생성자 함수가 (미래에) 생성할 인스턴스
Function.prototype.apply/call/bind 메서드에 의한 간접 호출 Function.prototype.apply/call/bind 메서드에 첫번째 인수로 전달한 객체