본문 바로가기
개발/javascript

22장 this - 바인딩 call, apply, bind

by 올럭Dev 2023. 12. 13.
728x90

일반 함수와 콜백 함수에서 this에 대해 알아보겠습니다.
Function.prototype.call, apply, bind 로 콜백함수에 this를 바인딩해보겠습니다.

목차 📑

  • 콜백 함수의 this 소개
  • this 바인딩 하기
  • Function.prototype call, apply 차이
  • Function.prototype bind

콜백함수의 this 소개

콜백 함수가 일반 함수로 호출된다면 콜백 함수 내부의 this에도 전역 객체가 바인딩됩니다. 어떠한 함수라도 일반 함수로 호출되면 this에 전역 객체가 바인딩됩니다.

var value = 1;
const obj = {
 value: 100,
 foo() {
  console.log('foo this: ', this); // { value: 100, foo: f}
  // 콜백함수 내부의 this에는 전역객체가 바인딩 됩니다.
  setTimeout(function(){
   console.log('callback this: ', this); // window
   console.log('callback this.value: ', this.value); // 1
  }, 100)
 
 }
}

obj.foo();

이처럼 일반 함수로 호출된 모든 함수(중첩함수, 콜백함수 포함) 내부의 this에는 전역 객체(window)가 바인딩됩니다.

this 바인딩 하기

메서드 내부의 중첩 함수나 콜백 함수의 this 바인딩을 메서드의 this바인딩과 일치 시키기 위한 3가지 방법을 알아보겠습니다.

var value = 1;
const obj = {
 value: 100,
 foo() {
  // 1. this를 할당
  // this 바인딩(obj)을 변수 that에 할당합니다.
  const that = this;  
  // 콜백함수 내부의 this 대신 that을 참조합니다.
  setTimeout(function(){
   console.log(that.value); // 100   
  }, 100);

  // 2. Function.prototype.bind 사용
  // 콜백 함수에 명시적으로 this 바인딩합니다.
  setTimeout(function(){
   console.log(this.value); // 100   
  }.bind(this), 100);

  // 3. 화살표 함수
  // 화살표 함수 내부의 this는 상위 스코프의 this를 가리킵니다.
  setTimeout(() => console.log(this.value), 100); 
 }
}

obj.foo();

Function.prototype call, apply 차이

apply, call, bind 메서드는 Function.prototype 의 메서드입니다.
Function.prototype.apply, Function.prototype.call 메서드는 this로 사용할 객체와 인수 리스트를 인수로 전달 받아 함수를 호출합니다.

/**
 * 주어진 this 바인딩과 인수 리스트 배열을 사용하여 함수를 호출합니다.
 * @param thisArg - this로 사용할 객체
 * @param argsArray - 함수에게 전달할 인수 리스트의 배열 또는 유사 배열 객체
 * @returns 호출된 함수의 반환값
 */
Function.prototype.apply(thisArg[, argsArray])

/**
 * 주어진 this 바인딩과 ,로 구분된 인수 리스트를 사용하여 함수를 호출합니다.
 * @param thisArg - this로 사용할 객체
 * @param arg1, arg2, ... - 함수에게 전달할 인수 리스트
 * @returns 호출된 함수의 반환값
 */
Function.prototype.call(thisArg[, arg1[, arg2[, ...]]])
function getThisBinding(){
 return this;
}

// this로 사용할 객체
const thisArg = { a: 1 };

console.log(getThisBinding()); // window

// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThisBinding 함수의 this에 바인딩합니다.
console.log(getThisBinding.apply(thisArg)); // { a: 1 }
console.log(getThisBinding.call(thisArg)); // { a: 1 }
function getThisBinding(){
 console.log(arguments);
 return this;
}

// this로 사용할 객체
const thisArg = {a: 1}

// getThisBinding 함수를 호출하면서 인수로 전달한 객체를 getThis Binding 함수의 this에 바인딩합니다.
// apply 메서드는 호출할 함수의 인수를 배열로 묶어 전달합니다.
console.log(getThisBinding.apply(thisArg, [1, 2, 3]));
// Arguments(3) [1,2,3, callee: f, Symbol(Symbol.iterator): f]
// { a: 1 }

// call 메서드는 호출할 함수의 인수를 쉼표로 구분한 리스트 형식으로 전달합니다.
console.log(getThisBinding.call(thisArg, 1, 2, 3));
// Arguments(3) [1,2,3, callee: f, Symbol(Symbol.iterator): f]
// { a: 1 }

Function.prototype bind

Function.prototype.bind 메서드는 apply와 call메서드와 달리 함수를 호출하지 않고 this로 사용할 개체만 전달합니다.

function getThisBinding(){
 return this;
}

const thisArg = { a: 1 };

// bind 메서드는 함수에 this로 사용할 객체를 전달합니다.
// bind 메서드는 함수를 호출하지 않습니다.
console.log(getThisBinding.bind(thisArg)); // getThisBinding
// bind 메서드는 함수를 호출하지 않으므로 명시적으로 호출해댜합니다.
console.log(getThisBinding.bind(thisArg)()) // { a: 1 }

bind메서드는 메서드의 this와 메서드 내부의 중첩 함수 또는 콜백 합수의 this가 불일치하는 문제를 해결하기 위해 유용하게 사용됩니다.

const person = {
 name: 'jeon',
 foo(callback){
  // 1
  setTimeout(callback, 100);
 }
};

person.foo(function() {
 console.log(`Hi! my name is ${this.name}.`); // Hi! my name is .
 // 일반함수로 호출된 콜백 함수 내부의 this.name은 브라우저 환경에서 window.name과 같습니다.
 // 브라우저 환경에서 window.name은 브라우저 창의 이름을 나타내는 빌트인 프로퍼티이며 기본값은 '' 입니다.
 // Node.js 환경에서 this.name은 undefined입니다.
})

콜백 함수 내부의 this를 외부 함수 내부 this와 일치시켜야 합니다.
이때 bind 메서드를 사용하여 this를 일치시킬 수 있습니다.

const person = {
 name: 'jeon', 
 foo(callback){
  // bind 메서드로 callback함수 내부의 this 바인딩을 전달합니다.
  setTimeout(callback.bind(this), 100)
  }
}
person.foo(function(){
 console.log(`Hi! my name is ${this.name}.`); // Hi! my name is jeon.
})

마치며 🍺

화살표 함수를 많이 사용해서 잘 사용하지는 않았지만, 옛날에 써본적이 있어서 한번 정리해봤습니다.
apply와 call의 차이는 apply는 배열, call은 나열식으로 인자를 넣어줍니다.

함께하면 좋은 글 😍

728x90