this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
자바스크립트에서 this가 가리키는 값은 다른 언어와 다르게 함수 호출방식(함수 호출 시점)에 의해 동적으로 결정된다. 또한 엄격 모드(strict mode)도 this가 가리키는 값에 영향을 준다.
전역에서의 this는 전역 객체 window를 가리킨다.
console.log(this); // window
객체 메서드 내부에서의 this는 메서드를 호출한 객체를 가리킨다.
const person = {
name: "홍길동",
getName() {
return this.name; // this는 person
}
}
console.log(person.getName()); // 홍길동
생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
}
// 인스턴스 생성
const person = new Person("미미");
console.log(person.getName()); // 미미
일반 함수 내부에서 this는 기본적으로 전역 객체 window를 가리킨다.
한편 엄격모드(strict mode)가 적용된 일반 함수 내부의 this는 undefined를 의미한다. 일반 함수 내부에서 this를 사용할 필요가 없기 때문이다.
function func() {
console.log(this); // window
}