this
- this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다. this를 통해 자신이 속한 객체 또한 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
단, this가 가리키는 값, 즉 this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.
const circle = {
radius : 5,
getDiameter() {
return 2 * this.radius;
}
};
console.log(circle.getDiameter());
- 일반함수로 호출시, 함수 내부의 this에는 전역 객체가 바인딩된다. 또한 중첩 함수, 콜백 함수 등 모든 함수 내부의 this에도 전역 객체가 바인딩된다.
function foo() {
console.log("foo's this :",this);
function bar(){
console.log("bar's this :",this);
}
bar();
}
foo();
- 메서드 내부의 this에는 메서드를 호출한 객체가 바인딩 된다.
const person = {
name : 'Lee',
getName(){
return this.name;
}
};
console.log(person.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());
- apply, call, bind 메서드는 Function.prototype의 메서드이다. apply와 call 메서드는 this로 사용할 객체와 인수 리스트를 인수로 전달받아 함수를 호출한다.
function getThisBinding(){
return this;
}
const thisArg = { a : 1 };
console.log(getThisBinding());
console.log(getThisBinding.apply(thisArg));
console.log(getThisBinding.call(thisArg));
- bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치 하는 문제를 해결하기 위해 유용하게 사용된다.
const person = {
name: "Lee",
foo(callback){
setTimeout(callback, 100);
}
};
person.foo(function(){
console.log(`Hi! my name is ${this.name}.`);
});
const person = {
name: "Lee",
foo(callback){
setTimeout(callback.bind(this), 100);
}
};
person.foo(function(){
console.log(`Hi! my name is ${this.name}.`);
});