동작을 나타내는 메서드는 자신이 속한 객체의 상태, 즉 프로퍼티를 참조하고 변경할 수 있어야 한다. 이때 메서드가 자신이 속한 객체의 프로퍼티를 참조하려면 먼저 자신이 속한 객체를 가리키는 식별자를 참조할 수 있어야 한다.
객체 리터럴 방식으로 생성한 객체의 경우 메서드 내부에서 메서드 자신이 속한 객체를 가리키는 식별자를 재귀적으로 참조할 수 있다.
const circle = {
radius: 5,
getDiameter() {
return 2 * circle.radius;
},
};
console.log(circle.getDiameter());
하지만 자기 자신이 속한 객체를 재귀적으로 참조하는 방식은 일반적이지 않으며 바람직하지도 않다. 생성자 함수 방식으로 인스턴스를 생성하는 경우를 생각해보자.
const circle = {
radius: 5,
getDiameter() {
return 2 * this.radius;
},
};
this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
this는 자바스크립트 엔진에 의해 암묵적으로 생성되며, 코드 어디서든 참조할 수 있다. 함수를 호출하면 arguments 객체와 this가 암묵적으로 함수 내부에 전달된다. 함수 내부에서 arguments 객체를 지역 변수처럼 사용할 수 있는 것처럼 this도 지역 변수처럼 사용할 수 있다. 단, this가 가리키는 값, 즉 this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.
// this는 어디든지 참조 가능하다.
// 전역에서 this는 전역 객체 window를 가리킨다.
console.log(this);
function sqaure(number) {
// 일반 함수 내부에서 this는 전역 객체 window를 가리킨다.
console.log(this); // window
return number * number;
}
sqaure(2);
const person = {
name: "Lee",
getName() {
// 메서드 내부에서 this는 메서드를 호출한 객체를 가리킨다.
console.log(this); // {name : "Lee", getName: f}
return this.name;
},
};
console.log(person.getName()); // Lee
function Person(name) {
this.name = name;
console.log(this); // Person {name : "Lee"}
}
const me = new Person("Lee");
자바스크립트의 this는 함수가 호출되는 방식에 따라 this에 바인딩될 값, 즉 this 바인딩이 동적으로 결정된다.
this 바인딩(this에 바인딩될 값)은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.
함수를 호출하는 방식
1. 일반 함수 호출
2. 메서드 호출
3. 생성자 함수 호출
4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출
// this 바인딩은 함수 호출 방식에 따라 동적으로 결정된다.
const foo = function () {
console.log(this);
};
// 동일한 함수도 다양한 방식으로 호출할 수 있다.
// 1. 일반 함수 호출
// foo 함수를 일반적인 방식으로 호출
// foo 함수 내부의 this는 전역 객체 window를 가리킨다.
foo(); // window
// 2. 메서드 호출
// foo 함수를 프로퍼티 값으로 호출
// foo 함수 내부의 this는 메서드를 호출한 객체 obj를 가리킨다.
const obj = { foo };
obj.foo(); // obj
// 3. 생성자 함수 소출
// foo 함수를 new 연산자와 함께 생성자 함수로 호출
// foo 함수 내부의 this는 생성자 함수가 생성한 인스턴스를 가리킨다.
new foo(); // foo {}
// 4. Function.prototype.apply/call/bind 메서드에 의한 간접 호출
// foo 함수 내부의 this는 인수에 의해 결정된다.
const bar = { name: "bar" };
foo.call(bar); // { name: 'bar' }
foo.apply(bar); // { name: 'bar' }
foo.bind(bar)(); // { name: 'bar' }
function foo3() {
console.log("foo3's this : ", this); // window
function bar3() {
console.log("bar3's this : ", this); // window
}
bar3();
}
foo3();
일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩 된다.
var value = 1;
const obj2 = {
value: 100,
foo() {
console.log("foo's this : ", this); // obj2
console.log("foo's this.value : ", this.value); // 100
// 메서드 내에서 정의한 중첩 함수
function bar() {
console.log("bar's this : ", this); // window
console.log("bar's this.value : ", this.value); // 1
}
// 메서드 내에서 정의한 중첩 함수도 일반 함수로 호출되면 중첩 함수 내부의 this에는
// 전역 객체가 바인딩된다.
bar();
},
};
obj2.foo();
콜백 함수가 일반 함수로 호출된다면 콜백 함수 내부의 this에도 전역 객체가 바인딩된다.
var value = 1;
const obj3 = {
value: 100,
foo() {
console.log("foo's this : ", this); // {value : 100, foo : f}
setTimeout(function () {
console.log("callback's this:", this); // window
console.log("callback's this.value:", this.value); // 1
}, 100);
},
};
obj3.foo();
이처럼 일반 함수로 호출된 모든 함수(중첩 함수, 콜백 함수 포함) 내부의 this에는 전역 객체가 바인딩된다.
객체 내부에 바인딩 하는 방법
// 1번
var value = 1;
const obj4 = {
value: 100,
foo() {
console.log("foo's this : ", this); // {value : 100, foo : f}
const that = this;
setTimeout(function () {
console.log("callback's this:", that); // {value : 100, foo : f}
console.log("callback's this.value:", that.value); // {value : 100, foo : f}
}, 100);
},
};
obj4.foo();
// 2번
var value = 1;
const obj5 = {
value: 100,
foo() {
console.log("foo's this : ", this); // {value : 100, foo : f}
setTimeout(
function () {
console.log("callback's this:", this); // {value : 100, foo : f}
console.log("callback's this.value:", this.value); // {value : 100, foo : f}
}.bind(this),
100
);
},
};
obj5.foo();
// 3번
var value = 1;
const obj6 = {
value: 100,
foo() {
console.log("foo's this : ", this); // {value : 100, foo : f}
setTimeout(() => {
console.log(this); // {value : 100, foo : f}
console.log(this.value); // 100
}, 100);
},
};
obj6.foo();
const person = {
name: "Lee",
getName() {
// 메서드 내부에서 this는 메서드를 호출한 객체를 가리킨다.
console.log(this); // {name : "Lee", getName: f}
return this.name;
},
};
console.log(person.getName()); // Lee
person 객체의 getName 프로퍼티가 가리키는 함수 객체는 person 객체에 포함된 것이 아니라 독립적으로 존재하는 별도의 객체다. getName 프로퍼티가 함수 객체를 가리키고 있을 뿐이다.
const person2 = {
name: "Lee",
getName() {
// 메서드 내부에서 this는 메서드를 호출한 객체를 가리킨다.
return this.name;
},
};
console.log(person2.getName()); // Lee
const person3 = {
name: "Kim",
};
person3.getName = person2.getName;
console.log(person3.getName()); // Kim