this
는 함수의 실행 문맥에 따라 동작하기 때문에, 함수를 호출하는 방법에 따라this
가 참조하는 객체가 달라질 수 있습니다. 이러한 특성 때문에 함수에서this
를 사용하는 부분에서 가장 큰 차이가 생길 수 있습니다. 특히, 객체의 메서드로 호출되는 함수에서this
를 사용하는 경우, 메서드를 호출한 객체에 따라this
가 참조하는 객체가 달라지므로 주의가 필요합니다.
this
는 JavaScript에서 현재 실행되는 함수에서 참조하는 객체를 나타내는 예약어입니다. 함수를 호출하는 방법에 따라 this
가 가리키는 객체가 달라질 수 있습니다.일반적으로 this
는 다음과 같이 동작합니다.
this
는 해당 객체를 참조합니다.const person = {
name: "John",
sayHi: function() {
console.log(`Hi, my name is ${this.name}`);
}
};
person.sayHi(); // Hi, my name is John
this
는 전역 객체(window 또는 global)를 참조합니다.function sayHi() {
console.log(`Hi, my name is ${this.name}`);
}
const name = 'John';
sayHi(); // Hi, my name is undefined
this
는 새로 생성된 객체를 참조합니다.function Person(name) {
this.name = name;
}
const person = new Person('John');
console.log(person.name); // John
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