this

장돌뱅이 ·2022년 1월 13일
0

JavaScript

목록 보기
23/46
  • this keyword는 호출객체(calling object, 메서드가 속해있는 객체를 의미.)의 속성에 접근할 수 있도록 하는 호출객체를 참조한다. 메서드에서 this 키워드를 사용하면, this의 값(value)은 호출객체가 된다.
const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(dietType);
  }
};
goat.diet(); 
// Output will be "ReferenceError: dietType is not defined"
const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet() {
    console.log(this.dietType);
  }
};
 
goat.diet(); 
// Output: herbivore

바로 위의 코드에서 호출 객체는 goat이다. 그리고 this를 이용하여 우리는 goat라는 객체와 goat의 속성에 접근한다.

const robot = {
  model: '1E78V2',
  energyLevel: 100,
  provideInfo() {
    return `I am ${this.model} and my current energy level is ${this.energyLevel}.`
  }
};

console.log(robot.provideInfo());
//I am 1E78V2 and my current energy level is 100. 반환

위 코드에서 this 키워드를 사용해야
provideInfo() 메서드가 robot이라는 객체의 속성에 접근할 수 있게 된다.

const goat = {
  dietType: 'herbivore',
  makeSound() {
    console.log('baaa');
  },
  diet: () => {
    console.log(this.dietType);
  }
};
 
goat.diet(); // Prints undefined

0개의 댓글

관련 채용 정보