const circle = {
key: 'value',
method() {
return this.key;
// return key; <- this가 없으면 레퍼런스에러 발생
},
};
console.log(circle.method()); // value
위의 예제에서 this가 가리키는 것은 circle(객체)


// 생성자 함수
function Circle(key) {
this.key = key;
}
Circle.prototype.getValue = function () {
return this.key;
};
// 인스턴스 생성
const instance1 = new Circle('인스턴스 1');
const instance2 = new Circle('인스턴스 2');
console.log(instance1.getValue()); // 인스턴스 1
console.log(instance2.getValue()); // 인스턴스 2
function foo() {
console.log(this);
}
// 1. 일반 함수 호출
foo(); //: 전역객체 window
// 2. 메서드 호출
const obj = { foo };
obj.name = 'name';
obj.foo(); //: 메서드를 호출한 obj
// 3. 생성자 함수 호출
const objConstructor = new foo();
//: 생성자 함수가 생성한 인스턴스 objConstructor

1. 일반 함수 호출
2. 메서드 호출
호출한객체.메서드() 일때, this는 호출한객체에 바인딩 된다.3. 생성자 함수 호출