[TIL] bind()

Captainjack·2021년 4월 12일
0

TIL

목록 보기
18/258

bind

The bind() method returns a new function, when invoked, has its this sets to a specific value.

The following illustrates the syntax of the bind() method:

fn.bind(thisArg[, arg1[, arg2[, ...]]])

In this syntax, the bind() method returns a copy of the function fn with the specific this value (thisArg) and arguments (arg1, arg2, …

When you pass a method an object is to another function as a callback, the this is lost.

so you have to use a bind() right this time.

-The bind() method creates a new function, when invoked, has the this sets to a provided value.

-The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.

from

https://www.javascripttutorial.net/javascript-bind/

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

이벤트 핸들러

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

let users = [
  {
    name: "Jack",
    skill: "eat a lot"
  },
  {
    name: "Rachel",
    skill: "act"
  },
  {
    name: "Tim",
    skill: "sleep"
  }
];

users.forEach((user) => {
  let btn = document.createElement("button");
  btn.textContent = user.name;
  btn.onclick = handleClick; // undefined;
  target.appendChild(btn);
});

soulution 1.

btn.onclick = handleClick.bind(null, user);

인자를 지정하며, 즉시 실행되지 않게 만듬.

soulution 1.


  btn.onclick = () => {
    handleClick(user)
  }

bind 사용없이 해결

setTimeout

setTimeout은 시간 지연을 일으킨 후 함수를 비동기적으로 실행하게 하는 함수입니다. 이 함수는 명시적으로 항상 window 객체를 this 바인딩하는 특징이 있습니다.

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() // 에러 발생!

solution 1

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

solution 2

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

-2021년 4월 13일 내용 정리 및 추가 예약

profile
til' CTF WIN

0개의 댓글