코어자바스크립트 3장 part3 (bind)

KHW·2021년 2월 22일
0

코어자바스크립트

목록 보기
7/19

bind 메소드

즉시 호출하지는 않고 넘겨 받은 this 및 인수들을 바탕으로 새로운 함수를 반환하기만 하는 메서드

목적
1. this를 미리 적용하는 것
2. 부분 적용 함수를 구현하는 것

ex)

var func = function (a,b,c,d){
  console.log(this,a,b,c,d);
}

var bindFunc = func.bind({x:1},4,5);		//새로운 함수 bindFunc를 반환
bindFunc(6,7) //	{x:1} 4 5 6 7 

만약, call/apply의 경우는 아래와 같다. ( 새로운 함수를 반환하지않고 바로 실행하기 때문)

var func = function (a,b,c,d){
  console.log(this,a,b,c,d);
}

 func.call({x:1},4,5,6,7);
var func = function (a,b,c,d){
  console.log(this,a,b,c,d);
}

 func.apply({x:1},[4,5,6,7]);

전역객체 VS 객체 구분하기

let obj = {
  
  normal : function(){
    console.log(this);
  },
  
  arrowFunc : ()=>{
    console.log(this);
  },
  
  innerFunc : function(){
    let innerF = function(){
      console.log(this);
    }
    innerF();
  },
  
  innerArrowFunc : function(){
    let innerF = ()=>{
      console.log(this);
    }	   
    innerF();
  }
}

obj.normal();	// {normal: ƒ, arrowFunc: ƒ, innerFunc: ƒ, innerArrowFunc: ƒ}
obj.arrowFunc();	//Window {0: global, 1: global, 2: Window, window: Window, self: Window, document: document, name: "", location: Location, …}
obj.innerFunc();	//Window {0: global, 1: global, 2: Window, window: Window, self: Window, document: document, name: "", location: Location, …}
obj.innerArrowFunc();	//{normal: ƒ, arrowFunc: ƒ, innerFunc: ƒ, innerArrowFunc: ƒ}
  1. obj.normal : 가장 쉬운 형태 this는 객체 obj를 나타낸다.
  2. obj.arrowFunc : 화살표 함수는 this바인딩을 하지 않으므로 this는 전역객체 (스코프 체인상 가장 가까운 전역객체에 접근)
  3. obj.innerFunc : 어떤 함수를 함수로서 호출한 경우 this는 전역객체를 참조한다.(예외 해당 함수가 화살표 함수일때)
  4. obj.innerArrowFunc : 접근 할 때 스코프 체인상 가장 가까운 this에 접근하므로 현재 가장가까운 obj를 나타낸다.

정리

객체의 프로퍼티에 화살표 함수로 등록된 this는 전역객체를 가르키고
객체의 프로퍼티에 함수로 등록된 내용의 콜백함수 혹은 내장함수가 화살표함수일 경우 스코프 체인상 가장 가까운 this에 접근한다.

call/apply/bind를 사용하는 이유

  1. 유사배열객체에 대해 배열 메서드를 적용
  2. 생성자 내부에서 다른 생성자를 호출 : 반복을 줄인다.
  3. 서로다른 this 객체를 바인딩

실제 1번은 ES6의 spread operator를 이용하면 되고( call/apply/bind를 쓸 필요 감소)
2번 혹은 3번일 경우에 적용시킨다.


출처

코어자바스크립트

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글