this는 함수가 실행될 때 결정되는 객체 참조값이다.
즉, 함수 내부에서 "지금 이 함수를 실행한 주체"를 가리킨다.
this는 함수가 만들어질 때 결정되지 않는다
함수가 호출되는 방식에 따라 결정된다
즉 this는 함수의 위치가 아니라 호출 방식(call-site)에 의해 결정된다.
const person = {
name: "홍길동",
greet() {
console.log(this.name);
},
};
person.greet();
실행 결과는 홍길동이다.
greet()를 person이 호출했기에
this는 person이 된다.
JavaScript에서 this는 크게 네 가지 상황으로 이해하는 것이 일반적이다.
function test() {
console.log(this);
}
test();
출력 결과로는 브라우저 환경 window가 나온다.
객체 없이 그냥 함수로 호출했을 경우,
전역 객체가 this가 된다.
const user = {
name: "철수",
sayName() {
console.log(this.name);
},
};
user.sayName();
결과는 철수가 된다.
user.sayName() 형태로, 점 앞의 객체(user)가 this가 된다.
function Person(name) {
this.name = name;
}
const p = new Person("홍길동");
console.log(p.name);
new로 호출하면 새로운 객체가 생성 되고,
this가 그 객체를 가리켜, 객체가 반환된다.
function greet() {
console.log(this.name);
}
const user = { name: "영희" };
greet.call(user);
결과는 영희가 나온다.
call/apply/bind로 this를 직접 지정할 수 있기 때문이다.
const person = {
name: "홍길동",
greet() {
setTimeout(function () {
console.log(this.name);
}, 1000);
},
};
person.greet();
결과는 undefined로,
setTimeout 안의 함수는 일반 함수 호출이기 때문이다.
즉 this는 전역 객체를 가리키게 된다.
Arrow Function은 자신만의 this를 가지지 않는다.
대신 외부 스코프의 this를 그대로 사용한다.
const person = {
name: "홍길동",
greet() {
setTimeout(() => {
console.log(this.name);
}, 1000);
},
};
person.greet();
결과는 홍길동,
바로 전 예제를 Arrow Function으로 바꿨을 뿐이다.
Arrow Function이 greet()의 this를 그대로 사용하기 때문이다.
this는 함수 내부에서 현재 실행 주체를 가리키는 참조값이다.this는 함수가 정의된 위치가 아니라 호출 방식에 의해 결정된다.객체.메서드() 형태로 호출되면 점 앞의 객체가 this가 된다.this가 전역 객체(window)가 된다.한 가지 더 짚어서
많이들 착각하는 포인트로,
많은 사람들이 this는 함수가 속한 객체라고 생각하는데,
실제로 this는 함수를 호출한 객체다.