
this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.this는 자바스크립트 엔진에 의해 암묵적으로 생성되며, 코드 어디서든 참조할 수 있다.arguments 객체와 this가 암묵적으로 함수 내부에 전달된다.arguments 객체를 지역 변수처럼 사용할 수 있는 것처럼 this도 지역 변수처럼 사용할 수 있다.this가 가리키는 값, 즉 this바인딩은 함수 호출 방식에 의해 동적으로 결정된다.this 바인딩은 함수 호출 방식, 즉 함수가 어떻게 호출되었는지에 따라 동적으로 결정된다.
함수를 호출하는 방식은 다음과 같이 다양하다.
기본적으로
this에는 전역 객체가 바인딩된다.
this는 의미가 없다.this에는 undefined가 바인딩된다.this에는 전역 객체가 바인딩된다.function foo() {
console.log("foo's this: ", this); // window
function bar() {
console.log("bar's this: ", this); // window
}
}
function foo() {
'use strict';
console.log("foo's this: ", this); // undefined
function bar() {
console.log("bar's this: ", this); // undefined
}
}
메서드 내부의
this는 메서드를 소유한 객체가 아닌 메서드를 호출한 객체에 바인딩된다.
const person = {
name: 'Lee',
getName() {
return this.name;
}
}
console.log(person.getName()); // Lee

생성자 함수 내부의
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.getDiamter()); // 10
console.log(circle2.getDiamter()); // 20
apply, call, bind 메서드는 Function.prototype의 메서드이므로 모든 함수가 상속받아 사용할 수 있다.apply, call 메서드는 this로 사용할 객체와 인수 리스트를 인수로 전달받아 함수를 호출한다.bind 메서드는 첫 번째 인수로 전달한 값으로 this 바인딩이 교체된 새로운 함수를 반환한다.function getThisBinding() {
console.log(arguments);
return this;
}
const thisArg = { a: 1 };
console.log(getThisBinding.apply(thisArg, [1, 2, 3]));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// { a: 1 }
console.log(getThisBinding.call(thisArg, 1, 2, 3));
// Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
// { a: 1 }
function getThisBinding() {
return this;
}
const thisArg = { a: 1 };
console.log(getThisBinding.bind(thisArg)); // getThisBinding
console.log(getThisBinding.bind(thisArg)()); // { a: 1 }
bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용된다.const person = {
name: 'Lee',
foo(callback) {
setTimeout(callback.bind(this), 100);
}
}
person.foo(function() {
console.log(`Hi! my name is ${this.name}.`); // Hi! my name is Lee
}
