this 키워드
function Circle(radius) {
????.radius = radius;
}
Circle.prototype.getDiameter = function () {
return 2 * ????.radius;
};
const circle = new Circle(5);
- this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다
- this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.
함수 호출 방식과 this 바인딩
일반 함수 호출
function foo() {
console.log("foo's this: ", this);
function bar() {
console.log("bar's this: ", this);
}
bar();
}
foo();
function foo() {
'use strict';
console.log("foo's this: ", this);
function bar() {
console.log("bar's this: ", this);
}
bar();
}
foo();
- 일반 함수로 호출하면 함수 내부의 this에는 전역 객체가 바인딩된다.
- strict mode가 적용된 일반 함수 내부의 this에는 undefined가 바인딩 된다.
var value = 1;
const obj = {
value: 100,
foo() {
console.log("foo's this: ", this);
setTimeout(function () {
console.log("callback's this: ", this);
console.log("callback's this.value: ", this.value);
}, 100);
}
};
obj.foo();
- 중첩 함수 또는 콜백 함수가 일반 함수로 호출된다면 this에는 전역 객체가 바인딩 된다.
- 어떠한 함수라도 일반 함수로 호출되면 this에 전역 객체가 바인딩 된다.
var value = 1;
const obj = {
value: 100,
foo() {
setTimeout(() => console.log(this.value), 100);
}
};
obj.foo();
- this에 전역객체가 바인딩 되지 않게 하려면 다른 변수에 할당 하여서 사용하거나 화살표 함수를 사용하여 해결한다.
메서드 호출
const person = {
name: 'Lee',
getName() {
return this.name;
}
};
console.log(person.getName());
const anotherPerson = {
name: 'Kim'
};
anotherPerson.getName = person.getName;
console.log(anotherPerson.getName());
const getName = person.getName;
console.log(getName());
- 메서드 내부의 this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩 된다는 것이다.
생성자 함수 호출
function Circle(radius) {
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
const circle1 = new Circle(5);
const circle2 = new Circle(10);
console.log(circle1.getDiameter());
console.log(circle2.getDiameter());
- new 연산자와 함께 생성자 함수를 호출하지 않으면 생성자 함수가 아니라 일반 함수로 동작한다.
const circle3 = Circle(15);
console.log(circle3);
console.log(radius);
Function.prototype.apply/call/bind 메서드에 의한 간접 호출
function getThisBinding() {
return this;
}
const thisArg = { a: 1 };
console.log(getThisBinding());
console.log(getThisBinding.apply(thisArg));
console.log(getThisBinding.call(thisArg));
- apply 와 call 메서드의 본직적인 기능은 함수를 호출하는것이다. 함수를 호출하면서 첫 번째 인수로 전달한 특정 객체를 호출한 함수의 this에 바인딩 한다.
const person = {
name: 'Lee',
foo(callback) {
setTimeout(callback.bind(this), 100);
}
};
person.foo(function () {
console.log(`Hi! my name is ${this.name}.`);
});
- 콜백 함수 내부의 this를 외부 함수 내부의 this와 일치시켜야 한다. 이때 bind를 사용하여 this 를 일치시킬 수 있다.