this
란this
를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조this
특징this
가 가리키는 값, 즉 this
바인딩은 함수 호출 방식에 의해 동적으로 결정this
바인딩this
와 this
가 가리킬 객체를 바인딩하는 것객체 리터럴의 메서드 내부에서의 this
는 메서드를 호출한 객체를 가리킴
// 객체 리터럴
const circle = {
radius: 5;
getDiameter() {
return 2 * this.radius; // this는 circle을 가리킴
}
}
console.log(circle.getDiameter()); // 10
생성자 함수 내부의 this
는 함수가 생성할 인스턴스를 가리킴
// 생성자 함수
function Circle(radius) {
this.radius = radius; // this는 생성자 함수가 생성할 인스턴스를 가리킴
}
Circle.prototype.getDiameter = function () {
return 2 * this.radius; // this는 생성자 함수가 생성할 인스턴스를 가리킴
};
// 인스턴스 생성
const circle = new Circle(5);
console.log(circle.getDiameter()); // 10
this
는 상황에 따라 가리키는 대상이 다르다.
참고 : 모던 자바스크립트 Deep Dive