JavaScript : this와 call, apply, bind

wonkeunC·2021년 12월 4일
0
post-thumbnail

this 란?

함수를 호출하는 객체를 의미합니다.
this의 값은 호출하는 방법에 의해서 결정된다는 것이 핵심이다. (누가 호출(실행) 했는가?)

this를 이용하여 함수 재사용하기.

✅ this를 사용하면 함수를 다른 객체에서도 재사용 할 수 있습니다.

function menuGlobal(){
  console.log("오늘의 메뉴는 "+ this.name);
}

------------------------------
              
var myFood = {
  name : "김치찌개",
  menu : menuGlobal
}

myFood.menu();

"결과 : 오늘의 메뉴는 김치찌개"

-------------------------------

var yourDinner = {
  name: '된장찌개',
  menu : menuGlobal
}

yourDinner.menu();

"결과 : 오늘의 메뉴는 된장찌개"

자동으로 값이 할당되는 this를 상황에 따라 제어할 수도 있어야 합니다.'
call, apply, bind가 대표적으로 존재합니다.


1. call()
this의 값을 바꿀 수도 있고, 함수를 실행할 때 사용할 인수도 전달할 수 있습니다.

call() 메서드는 함수가 사용할 인자를 전달할 수 있기 때문에 인자를 받을 weatherCondition으로 지정해주었다.

// code
function weatherGlobal(weatherCondition) {
  console.log('오늘의 날씨는' + weatherCondition + this.weather) 
  // 여기서 this는 맨 밑에 weatherGlobal을 호출한 .call( 객체, ___ ) 객체가 가지고 있는 weather을 바라본다.
}

var today = {     <-- 함수가 따로 필요 없는 객체를 생성.
  weather : '맑음 입니다.'
}

var tomorrow = {
  weather : '눈 입니다'
}

weatherGlobal.call(today, ' 30도 ')  "결과 : '오늘의 날씨는 30도 맑음 입니다.'"
// weatherGlobal함수는 call()안에 넣어준 객체를 바라보게 된다.
// 또한 인자값(weatherCondition)을 넣을 수 있다.

weatherGlobal.call(tomorrow, ' -12도 ')  "결과 : '오늘의 날씨는 -12도 눈 입니다'"

call()을 통해서 this에 대상이되는 객체를 지정해 보았습니다.



2. apply()
함수를 실행할 때 인수를 배열에 묶어 한번에 전달합니다.

function weatherGlobal(weather, temperature) { // 인수로 배열을 전달할 것이기 때문에 두개의 인자를 만들었다.
  [weather, temperature].forEach(function(el){
   console.log("오늘의 날씨는 "+ this.city + el);
  },this)  // forEach 같은 반복문에서 this를 전달 받으려면 두번째 인자로 this를 선언해주어야 한다.
// this를 선언해주지 않으면! 
// forEach안에 실행되는 function은 그 안에 this로 불러오는 객체를 바라보게 되는데 this를 선언하지 않으면
// 전역 객체인 window객체를 불러오게 된다.
}

var today = {
 city : "London"
}

var tomorrow = {
 city : "Sydney"
}

weatherGlobal.apply(today, [" 비"," -4도"])

결과 : 
'오늘의 날씨는 London 비'
'오늘의 날씨는 London -4도'"


weatherGlobal.apply(tomorrow, [" 폭우"," 10도"])

결과 :
'오늘의 날씨는 Sydney 폭우'
'오늘의 날씨는 Sydney 10도'

🔎 call() 과 apply()의 차이점
call()은 함수를 실행 할 때 전달할 인수를 하나 하나 전달한다면
apply()는 전달할 인수를 배열로 묶어 한번에 전달합니다. 그래서 인수를 두개만 사용합니다.
인수를 배열로 보낸다는 점을 제외하고는 call()apply()는 동일한 기능을 수행합니다.



3. bind()
es5에서 문법이 추가 되었습니다.
this값을 어디서 사용하든 호출 객체가 바뀌지 않게 고정시켜버립니다.

function weatherGlobal(weather){
  console.log("오늘의 날씨는 "+ weather + this.city);
}

var today = {
 city : "London"
}

var tomorrow = {
 city : "Sydney"
}

var weatherBindToday = weatherGlobal.bind(today);
// weatherBindToday 변수에 weatherGlobal 함수 안에 있는 this의 값을 bind를 사용해서 today로 정의해버렸다.
var weatherBindTomorrow = weatherGlobal.bind(tomorrow);



weatherBindToday('맑음 '); // 결과 : '오늘의 날씨는 맑음 London'
weatherBindTomorrow('폭우 ') // 결과 : '오늘의 날씨는 폭우 Sydney'

🔎 bind()만의 파워를 살펴보자


"var today 변수에 새로운 key 값을 설정하고 새로 만든 key의 값으로 weatherBindTomorrow의 함수를 사용할 수 있다."

function weatherGlobal(weather){
  console.log("오늘의 날씨는 "+ weather + this.city);
}

var today = {
 city : "London"
}

var tomorrow = {
 city : "Sydney"
}

var weatherBindToday = weatherGlobal.bind(today);
var weatherBindTomorrow = weatherGlobal.bind(tomorrow);

today.newKeyBox = weatherBindTomorrow;
console.log(today) --> {city : 'London', newBox: f}

// today 변수 안에 newBox 키가 생성되고 값으로는 Sydney의 값을 갖고 있는 weatherBindTomorrow 함수가 들어갔다.

today.newKeyBox('나는야 시드니 ') // 결과 : "오늘의 날씨는 나는야 시드니 Sydeny"

이렇게 다른 객체에서 실행되는 함수도 그 함수만을 바라보는 객체를 고정시켜버릴 수 있다.



+ 화살표 함수의 this
화살표 함수의 this는 일반적인 this처럼 함수를 호출한 객체를 할당하지 않고,
바로 상위 Scope의 this를 할당합니다.


📝 this 정리하기

  • this는 함수를 호출하는 객체를 의미합니다.
  • call()과 apply()는 this에 할당되는 객체를 지정할 수 있습니다.
  • bind() 메서드는 this에 할당되는 객체가 고정된 새로운 함수를 생성합니다.
  • 화살표 함수에서 this는 상위 Scope의 객체를 할당 받습니다.
profile
개발자로 일어서는 일기

0개의 댓글