[JS] 함수 메서드 bind

Fleuve·2020년 10월 2일
0
post-thumbnail

bind는 call,apply와 다르게 함수를 바로 실행시키지 않고 this의 값이 바인딩된 함수를 리턴한다.

아래 예재를 보면 bind를 사용하면 함수는 실행이 되지 않았지만 boundFn을 실행시키면 원하는 결과가 나오는 것을 볼 수 있다.

function add(x,y) {
  this.val = x + y;
  console.log(this.val);
}

let obj = {
  val: 0
}

let boundFn = add.bind(obj, 2, 8);// 함수가 실행되지 않는다.
boundFn();// 10
  • bind로 setTimeout 사용시 this 전달하기

function Box(w,h) {
  this.width = w;
  this.height = h;
  this.getArea = function() {
    return this.width * this.height;
  }
  this.printArea = function() {
    console.log(this.Area);
  }
}
let box = new Box(100, 50);
box.printArea() // 5000
setTimeout(box1.printArea, 4000)//TypeError

setTimeout을 사용하면 TypeError이 뜨는 것을 확인할 수 가있다. 왜 이런 결과가 나오는 것일까?
new 키워드를 사용하여 함수를 호출하면 this는 box를 가리키고 있어 5000이라는 결과를 반환하지만 setTimeout을 사용하면 this는 window객체를 가리키게 된다. 그렇기 때문에 TypeError가 발생하게 된다. 그렇다면 setTimeout을 사용하였을때 this를 전달하려면 어떻게 해야할까?

setTimeout(box.printArea.bind(box), 4000)// 4초 뒤 5000 출력

이렇게 bind를 사용하여 명시적으로 this의 값을 인스턴스 box로 지정하면 4초 뒤 원하는 결과를 얻어 낼수 있다.

  • bind로 커링 구현하기

    커링: 인자 여러 개를 받는 함수를 인자를 하나를 받는 함수로 바꾸는 것을 말한다.

function fullName(firstName, lastName) {
	return `${firstName} ${lastName}`;
}

let name = fullName(null, 'Michael');
name('Jackson'); // 'Michael Jackson'

이렇게 바인딩을 사용하여 커링을 구현할 수 있다.

0개의 댓글