Menu
Coddy logo textTech

this 키워드 이해하기

Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 56개 중 3번째.

JavaScript의 this 키워드는 현재 코드를 실행하고 있는 객체를 가리킵니다. 이를 통해 현재 객체의 속성과 메서드에 액세스할 수 있습니다.

기본 객체부터 시작해 보겠습니다.

let person = {
  name: "John",
  age: 30,
  greet: function() {
    console.log("Hello, my name is " + this.name);
  }
};

이 예제에서 greet 메서드를 호출하면:

person.greet();

출력은 다음과 같습니다:

Hello, my name is John

여기서 greet 메서드 안의 this.nameperson 객체의 name 속성을 가리킵니다.

challenge icon

챌린지

Add getStatus라는 method를 player 객체에 추가하여 this 키워드를 사용해 player의 이름과 health가 포함된 string을 returns하도록 하세요.

예상 Output 형식:
"Knight has 70 health"

직접 해보기

const player = {
    name: "Knight",
    health: 100,
    
    takeDamage: function(damage) {
        this.health -= damage;
    },
    
    // TODO: 여기에 플레이어의 name과 health가 포함된 문자열을 반환하는 getStatus 메서드를 추가하세요

};


// 테스트
player.takeDamage(30);
console.log(player.getStatus()); // Should output: "Knight has 70 health"
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 JavaScript 컴파일러