본문 바로가기

Programming/TIL

.bind Method

bind 메소드

.bind는 .call과 유사하게 this 및 인자를 바인딩하나, 당장 실행하는 것이 아닌 바인딩된 함수를 리턴하는 함수이다.

첫번째 인자는 this, 두번째 인자부터는 필요한 파라미터를 전달합니다.

fn.bind(this값, 인자1, 인자2, ...)

.bind의 사용 예시를 살펴보자.

bind는 이벤트 핸들러에서 이벤트 객체 대신 다른 값을 전달하고자 할 때 유용하다.

예시1.

<div id="target"></div>
let target = document.querySelector('#target')
let users = ['김코딩', '박해커', '최초보']

users.forEach(function(user) {
  let btn = document.createElement('button')
  btn.textContent = user
  btn.onclick = handleClick
  target.appendChild(btn)
});
  
  
function handleClick() {
  console.log(this)
}

위의 경우, 각각의 btn들을 클릭하면, btn 태그 자체가 콘솔에 표시 될 것이다.

만약, 이 값을 바꾸고 싶다면 .bind를 이용해 this로 넘기거나 인자로 보낼 수 있다.

  btn.onclick = handleClick.bind(user) // 이렇게 바꿔볼 수 있다.

예시2.

class Rectangle {
  constructor(width, height) {
    this.width = width
    this.height = height
  }
  
  getArea() {
    return this.width * this.height
  }

  printArea() {
    console.log('사각형의 넓이는 ' + this.getArea() + ' 입니다')
  }
  
  printSync() {
    // 즉시 사각형의 넓이를 콘솔에 표시.
    this.printArea()
  }
  
  printAsync() {
    // 1초 후 사각형의 넓이를 콘솔에 표시.
    setTimeout(this.printArea, 2000)
  }
}

let box = new Rectangle(40, 20)
box.printSync() // '사각형의 넓이는 800 입니다'
box.printAsync() // 에러 발생!

위 코드에서 발생되는 에러를 해결하기 위해 .bind를 사용할 수 있다.

* printAsync() 부분을 아래와 같이 바꿔보자.

printAsync() {
  // 1초 후 사각형의 넓이를 콘솔에 표시합니다
  setTimeout(this.printArea.bind(this), 2000)
}

아래와 같이 화살표 함수를 넣어볼 수도 있다.

printAsync() {
  // 1초 후 사각형의 넓이를 콘솔에 표시합니다
  setTimeout(() => {
    this.printArea()
  }, 2000)
}

'Programming > TIL' 카테고리의 다른 글

Data Structure(1) Stack & Queue  (0) 2020.12.03
ESlint  (0) 2020.12.02
.call & .apply Methods  (0) 2020.12.01
[this] Keyword  (0) 2020.12.01
Arrow Function  (0) 2020.12.01