JavaScript This keyword


this 키워드는 자바스크립트에서 매우 중요하며, 함수가 어떻게 호출되는지에 따라 동적으로 바인딩되는 값입니다. this는 실행 컨텍스트에 따라 결정되며, 주로 메소드 호출 시, 생성자 함수 내에서, 또는 전역 컨텍스트에서 사용될 수 있습니다.

메소드 호출에서의 this

메소드 내부에서 this는 해당 메소드를 호출한 객체를 가리킵니다.

const person = {
    name: 'John',
    greet: function() {
        console.log(`Hello, my name is ${this.name}.`);
    }
};

person.greet(); // 출력: "Hello, my name is John."

함수 호출에서의 this

일반 함수 내부에서 this는 실행 컨텍스트에 따라 다르게 동작합니다. 기본적으로 전역 객체(window)를 가리키지만, strict mode에서는 undefined가 됩니다.

function showThis() {
    console.log(this);
}

showThis(); // 출력: 전역 객체 (브라우저에서는 window 객체)

생성자 함수에서의 this

생성자 함수 내부에서 this는 새로 생성된 인스턴스를 가리킵니다.

function Person(name, age) {
    this.name = name;
    this.age = age;
}

const john = new Person('John', 30);
console.log(john.name); // 출력: "John"

직접 바인딩하기 (bind, call, apply)

bind, call, apply 메소드를 사용하여 this를 직접 지정할 수 있습니다.

bind 메소드

const person = {
    name: 'John',
    greet: function() {
        console.log(`Hello, my name is ${this.name}.`);
    }
};

const greetFunc = person.greet.bind(person);
greetFunc(); // 출력: "Hello, my name is John."

call 메소드

function greet() {
    console.log(`Hello, my name is ${this.name}.`);
}

const person = {
    name: 'John'
};

greet.call(person); // 출력: "Hello, my name is John."

apply 메소드

function greet(message) {
    console.log(`${message}, my name is ${this.name}.`);
}

const person = {
    name: 'John'
};

greet.apply(person, ['Hello']); // 출력: "Hello, my name is John."

Arrow 함수에서의 this

Arrow 함수 내부에서 this는 언제나 자신이 정의된 환경(lexical context)의 this를 따릅니다. Arrow 함수는 자신만의 this를 가지지 않고 외부 함수의 this를 공유합니다.

const person = {
    name: 'John',
    greet: function() {
        setTimeout(() => {
            console.log(`Hello, my name is ${this.name}.`);
        }, 1000);
    }
};

person.greet(); // 출력: "Hello, my name is John." (1초 후)

this 바인딩 순서

  1. 전역 컨텍스트: 전역 코드에서의 this는 전역 객체를 가리킵니다 (브라우저 환경에서는 window).
  2. 함수 내부: 일반적인 함수 호출 시, this는 전역 객체를 가리킵니다 (strict mode에서는 undefined).
  3. 메소드 호출: 객체의 메소드 내부에서 this는 해당 객체를 가리킵니다.
  4. 생성자 함수: 생성자 함수 내부에서 this는 새로 생성된 인스턴스를 가리킵니다.
  5. Arrow 함수: Arrow 함수 내부에서 this는 자신이 정의된 환경의 this를 따릅니다.

결론

this는 자바스크립트에서 매우 중요한 개념으로, 실행 컨텍스트에 따라 동적으로 바인딩됩니다. 메소드 호출 시 객체를 가리키거나, 생성자 함수에서는 새로운 인스턴스를 가리키도록 설계되어 있습니다. Arrow 함수는 자신만의 this를 가지지 않고 외부 환경의 this를 사용합니다. 함수 내부에서 this가 어떻게 동작하는지 이해하면 자바스크립트에서 코드를 효율적으로 작성하는 데 큰 도움이 됩니다.


Leave a Reply

Your email address will not be published. Required fields are marked *