[기술면접] this

한재창·2023년 3월 31일
0
post-thumbnail

this 가 동작하는 원리와 용법을 아는대로 설명해주세요. 평소 코드 중에서는 어떤 부분에서 가장 큰 차이가 생기나요?

this는 함수의 실행 문맥에 따라 동작하기 때문에, 함수를 호출하는 방법에 따라 this가 참조하는 객체가 달라질 수 있습니다. 이러한 특성 때문에 함수에서 this를 사용하는 부분에서 가장 큰 차이가 생길 수 있습니다. 특히, 객체의 메서드로 호출되는 함수에서 this를 사용하는 경우, 메서드를 호출한 객체에 따라 this가 참조하는 객체가 달라지므로 주의가 필요합니다.

this

  • this는 JavaScript에서 현재 실행되는 함수에서 참조하는 객체를 나타내는 예약어입니다. 함수를 호출하는 방법에 따라 this가 가리키는 객체가 달라질 수 있습니다.

일반적으로 this는 다음과 같이 동작합니다.

  1. 함수가 객체의 메서드로 호출될 때, this는 해당 객체를 참조합니다.
const person = {
  name: "John",
  sayHi: function() {
    console.log(`Hi, my name is ${this.name}`);
  }
};

person.sayHi(); // Hi, my name is John
  1. 함수가 일반적인 함수로 호출될 때, this는 전역 객체(window 또는 global)를 참조합니다.
function sayHi() {
  console.log(`Hi, my name is ${this.name}`);
}

const name = 'John';
sayHi(); // Hi, my name is undefined
  1. 함수가 생성자로 호출될 때, this는 새로 생성된 객체를 참조합니다.
function Person(name) {
  this.name = name;
}

const person = new Person('John');
console.log(person.name); // John
  1. call(), apply(), bind() 메서드를 사용하여 this의 값을 지정할 수 있습니다.
const person1 = { name: 'John' };
const person2 = { name: 'Mike' };

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

sayHi.call(person1); // Hi, my name is John
sayHi.apply(person2); // Hi, my name is Mike

const sayHiPerson1 = sayHi.bind(person1);
sayHiPerson1(); // Hi, my name is John
profile
취준 개발자

0개의 댓글