this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
메서드는 자신이 속한 객체의 상태, 즉 프로퍼티를 참조하고 변경할 수 있어야 한다.
메서드가 자신이 속한 객체의 프로퍼티를 참조하려면 먼저 자신이 속한 객체를 가리키는 식별자를 참조할 수 있어야 한다. 이 것을 위해 도와주는 것이 this다.
const circle = {
// 프로퍼티: 객체 고유의 상태 데이터
redius: 5,
// 메서드: 상태 데이터를 참조하고 조작하는 동작
getDiameter() {
return 2 * circle.radius;
}
}
console.log(circle.getDiameter()); // 10
이 예제의 경우 객체 리터럴 방식으로 객체를 생성한 후 메서드 내에서 자신이 속한 객체를 가리켜 재귀적으로 참조하였다.
하지만 자기 자신이 속한 객체를 재귀적으로 참조하는 방식은 일반적이지 않으며 바람직하지 않다.
보통의 경우엔 생성자 함수 방식으로 인스턴스를 생성한다.
function Circle(radius) {
????.radius = radius;
}
Circle.property.getDiameter = function() {
return 2 * ????.radius;
}
const circle = new Circle(5);
해당 예제에서 생성자 함수(Circle)가 정의될 시점에는 아직 인스턴스를 생성하기 이전이므로 자신을 가리키는 식별자를 알 수 없다.
생성자 함수의 프로퍼티나 메서드를 사용하려면 자신이 어떤 객체인지를 알고 있어야 올바르게 사용할 수 있는데 이때 필요한 것이 this
다.
this는 자신이 속한 객체 또는 자신이 생성할 인스턴스를 가리키는 자기 참조 변수다.
this를 통해 자신이 속한 객체 또는 자신이 생성할 인스턴스의 프로퍼티나 메서드를 참조할 수 있다.
this는 메서드를 호출한 객체를 가리키며 생성자 함수가 생성할 인스턴스를 가리킨다.
const circle = {
redius: 5,
getDiameter() {
return 2 * this.radius; // this = circle
}
}
----------------------------------------------------------
function Circle(radius) {
this.radius = radius; // this = 생성될 인스턴스인 circle
}
Circle.property.getDiameter = function() {
return 2 * this.radius; // this = 생성될 인스턴스인 circle
}
const circle = new Circle(5);
이때 this가 식별자(객체 또는 인스턴스)와 연결되는 과정을 바인딩
이라고 하는데 this 바인딩은 함수 호출 방식에 의해 동적으로 결정된다.
함수 호출 방식은 다음과 같다.
function foo() {
console.log("foo's this: ", this); // window
function bar() {
console.log("bar's this: ", this); // window
}
bar();
}
foo();
일반 함수를 호출할 시에는 this는 기본적으로 전역 객체가 바인딩된다.
this는 객체의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수이므로 객체를 생성하지 않는 일반 함수에서 this는 의미가 없다.
객체 안에 존재하는 메서드 내에서 정의한 중첩 함수도 일반 함수로 호출되면 중첩 함수 내부의 this는 전역 객체가 바인딩된다.
어떤 함수라도 일반 함수로 호출되면 전역 객체가 바인딩 된다.
화살표 함수는 선언된 스코프의 상위 스코프를 this로 가리킨다.
const foo = () => {
console.log(this);
}; // window
foo();
----------------------------------------------
const obj = {
value: 100,
foo() {
setTimeout(() => console.log(this, this.value), 0); // {value: 100, foo: ƒ} , 100
}
}
obj.foo();
메서드 내부의 this는 메서드를 호출한 객체에 바인딩된다.
const person = {
name: 'Lee',
getName() {
// 호출한 객체에 this가 바인딩 된다.
return this.name;
}
}
console.log(person.getName()); // Lee
생성자 함수 내부의 this에는 생성자 함수가 (미래에) 생성할 인스턴스가 바인딩된다.
// 생성자 함수
function Circle(radius) {
this.radius = radius;
this.getDiameter = function() {
return 2 * this.radius;
}
this.checkThis = function() {
return this;
}
}
const circle1 = new Circle(5);
const circle2 = new Circle(10);
console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20
console.log(circle1.checkThis()); // {radius: 5, getDiameter: ƒ, checkThis: ƒ}
console.log(circle2.checkThis()); // {radius: 10, getDiameter: ƒ, checkThis: ƒ}
new 연산자와 함께 호출하지 않으면 생성자 함수로 동작하지 않는다. 즉, 일반적인 함수의 호출이 된다.
const circle3 = Circle(15);
console.log(circle3); // undefined
console.log(circle1); // {radius: 5, getDiameter: ƒ, checkThis: ƒ}
apply와 call은 함수를 호출하는 기능인데, 함수의 인자로 this로 사용할 객체와 함수에게 전달할 리스트, 리스트의 배열 또는 유사 배열 객체를 인자로 받아 주어진 this를 바인딩 하는 함수이다.
Function.prototype.apply(thisArg[, argsArray])
Function.prototype.call(thisArg[, arg1[, arg2[, ..]]])
function getThisBinding() {
return this;
}
// this로 사용할 객체
const thisArg = { a : 1 };
console.log(getThisBinding()); // window
console.log(getThisBinding.apply(thisArg)); // {a: 1}
console.log(getThisBinding.call(thisArg)); // {a: 1}
함수를 호출하는데 인자로 받은 객체를 this로 삼아 호출하는 것이다.
두 메서드는 호출할 함수에 인수를 전달하는 방식만 다를 뿐 동일하게 동작한다.
bind 메서드는 apply와 call 메서드와 달리 함수를 호출하지 않는다.
첫 번째 인수로 전달한 값으로 this 바인딩이 교체된 함수를 새롭게 생성해 반환한다.
function getThisBinding() {
return this;
}
// this로 사용할 객체
const thisArg = { a : 1 };
// getBinding 함수를 새롭게 생성해 반환한다.
console.log(getThisBinding().bind(thisArg)); // getThisBinding
// 함수를 호출하지 않으므로 명시적으로 호출해야 한다.
console.log(getThisBinding().bind(thisArg)()); // {a: 1}
bind 메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 함수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용된다.
const person = {
name: 'Lee',
foo(callback) {
setTimeoue(callback, 0);
}
}
person.foo(function() {
console.log(`Hi! my name is ${this.name}.`) // Hi! my name is .
// 일반 함수로 호출된 콜백 함수 내부의 this.name은 브라우저 환경에서 window.name과 같다.
// window.name에는 기본값으로 ''가 들어가 있다.
// node.js 환경에서는 undefined다.
}){
}
------------------------------------------------------------------------------------
const person = {
name: 'Lee',
foo(callback) {
setTimeoue(callback.bind(this), 0);
}
}
person.foo(function() {
console.log(`Hi! my name is ${this.name}.`) // Hi! my name is Lee.
}){
}
이처럼 bind 메서드를 사용하면 콜백 함수의 내부 this와 외부 함수 내부의 this를 일치하도록 할 수 있다.