1. function 함수와 this 키워드

this 는 생성자 혹은 메서드에서 객체를 가리킬 때 사용하는 키워드이다.

function 함수에서 this 키워드를 사용하면 자신이 속해있는 객체(Object)를 참조할 수 있게 된다.

그래서, 객체의 메서드에서 this 키워드를 사용하면 속해 있는 객체 내의 다른 property 로 접근할 수 있게 된다.

function 함수에서 this 가 가

[예시 1 - function 함수가 객체의 메서드일 때, this 키워드가 가리키는 대상]

const person = {
    first: 'Dong Kyoo',
    last: 'Lee',
    fullName: function() {
        // undefined, 에러
        // console.log(first, last);

        // this => person
        console.log(this.first, this.last);
    }
}

// Dong Kyoo Lee
person.fullName();

[예시 2 - 메서드에서 this 키워드가 가리키는 대상]

const hen = {
    name: 'Helen',
    eggCount: 0,
    layAnEgg() {
        // this => hen
        this.eggCount += 1;
        return 'EGG';
    }
}

console.log(hen.name); // "Helen"
console.log(hen.eggCount); // 0
console.log(hen.layAnEgg()); // "EGG"
console.log(hen.layAnEgg()); // "EGG"
console.log(hen.eggCount); // 2
  • 전역 스코프에서 선언된 function 함수의 this 는 전역 객체인 window를 가리킨다.
function thisInFunction() {
    // this => window
    console.log(this);
}

// window
thisInFunction();

2. 화살표 함수와 this 키워드

화살표 함수와 this 키워드는 다음과 같은 특성을 가진다.

  • 화살표 함수의 this 는 ‘상위 스코프의 this’를 가리킨다.
  • 화살표 함수는 스스로의 this, argument 를 가지지 않는다.
  • 화살표 함수는 생성될 때 this 가 결정된다.
  • 화살표 함수가 어떻게 사용되건, 호출되건, this 는 바뀌지 않는다.

만약, 전역 스코프에 선언된 객체의 메서드로 ‘화살표 함수’를 사용한다면, 화살표 함수의 특성상 자신만의 this 를 갖지 않기 때문에, 상위 스코프의 this, 즉 전역 스코프를 가리키게 되고, 따라서 전역 객체인 window를 가리키게 된다.

const person = {
    firstName: 'Dong Kyoo',
    lastName: 'Lee',
    fullName_1: function() {
        // function 함수의 this 키워드는 자신이 종속된 객체(person)을 가리킴
        console.log(this);
        return this.firstName + this.lastName;
    },
    fullName_2: () => {
        // 화살표 함수의 this 키워드는 상위스코프(person)의 this, 즉 window를 가리킴
        console.log(this);
        return this.firstName + this.lastName;
    },
}

// Dong Kyoo Lee
console.log(person.fullName_1());

// undefined, 에러
console.log(person.fullName_2());

그렇다면, 메서드인 화살표 함수의 this 가 자신이 속한 객체(person)을 가리키려면 어떻게 해야할까?

답은 화살표 함수를 둘러싼 스코프를 추가하면 된다.

const person = {
	...
    fullName_3: function() {
        // 화살표 함수의 this 키워드는 상위스코프(fullName_3)의 this, 즉 person을 가리킴
        const say = () => this.firstName + this.lastName;
        console.log(say());
    }
}
...

// Dong Kyoo Lee
person.fullName_3();

[정리]

  • function 함수는 함수가 어떻게 실행되는가에 따라서 this 가 가리키는 객체가 동적으로 바뀐다. 이렇게 동적으로 this 가 가리키는 객체가 달라지면, 문제가 발생할 수 있다. (아직은 클래스를 다루지는 않았지만, 클래스로 인스턴스를 만들어 메서드를 호출 하는 경우 등)
  • 이렇게 동적으로 바뀌는 this 를 보완하기 위해, 화살표 함수의 경우 화살표 함수가 정의된 곳의 문맥에 의해서 this 를 고정할 수 있다.
  • this 가 예상한 대로 동작하지 않는다면 함수의 실행 환경을 생각해보아야 한다.

댓글남기기