JavaScript에서 객체는 데이터와 함께 함수(메소드)를 가질 수 있는 구조입니다. 메소드는 객체의 프로퍼티가 함수로 설정된 것을 의미합니다. this 키워드는 일반적으로 그 함수가 속한 객체를 참조합니다. this의 정확한 값은 함수 호출 방식에 따라 달라집니다.

메소드 정의

객체 내에서 함수를 메소드로 정의하는 것은 객체의 프로퍼티에 함수를 할당하는 것을 의미합니다.

 

예제: 메소드 정의

const dog = {
    name: "Buddy",
    breed: "Golden Retriever",
    greet: function() {
        console.log(`Woof! My name is ${this.name} and I am a ${this.breed}.`);
    }
};

dog.greet();  // Woof! My name is Buddy and I am a Golden Retriever.

 

이 예제에서 greet 메소드는 dog 객체의 일부로 정의되어 있으며, this를 사용하여 객체의 name과 breed 프로퍼티에 접근합니다.

이해하기 쉬운 this 예제

this의 값은 함수가 호출되는 방식에 따라 달라집니다. 객체의 메소드로서 함수가 호출될 때, this는 그 메소드를 호출한 객체를 참조합니다.

 

예제: this의 사용

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

person.greet();  // Hello, my name is Alice

 

this의 문맥 이해

function showDetails() {
    console.log(`Name: ${this.name}, Age: ${this.age}`);
}

const person1 = {
    name: "Bob",
    age: 30,
    details: showDetails
};

const person2 = {
    name: "Charlie",
    age: 25,
    details: showDetails
};

person1.details();  // Name: Bob, Age: 30
person2.details();  // Name: Charlie, Age: 25

 

이 예제들에서 this는 메소드가 호출된 객체 (person1, person2)를 참조합니다. 동일한 함수 showDetails를 다른 객체의 메소드로 사용했을 때 this는 각 객체에 맞게 해석됩니다.

 

주의: this와 화살표 함수

화살표 함수에서는 this가 다르게 동작합니다. 화살표 함수는 자신의 this를 가지지 않고, 그 대신 함수가 생성된 스코프의 this를 "상속" 받습니다.

 

예제: 화살표 함수와 this

const cat = {
    name: "Whiskers",
    actions: ['purr', 'meow', 'sleep'],
    showActions: function() {
        this.actions.forEach(action => {
            console.log(`${this.name} likes to ${action}.`);
        });
    }
};

cat.showActions();
Whiskers likes to purr.
Whiskers likes to meow.
Whiskers likes to sleep.

 

이 경우, 화살표 함수 내부의 this.name은 cat 객체를 참조합니다. 화살표 함수가 일반 함수 스코프 내에서 정의되었기 때문에, 주변 환경인 showActions 함수의 this 값을 사용합니다.

 

이러한 예제들은 this 키워드와 메소드의 사용 방법을 이해하는 데 도움이 되며, JavaScript에서 객체를 더 효과적으로 활용할 수 있게 합니다. 이 주제를 통해 객체의 메소드를 정의하고, this의 동작 원리를 파악하는 데 익숙해지는 것이 중요합니다.

+ Recent posts