Skip to content

funtion.prototype.bind는 언제 사용할까? #48

@soonitoon

Description

@soonitoon

다른 객체에서 메소드를 빌려 사용할 때

const person = {
  firstName: "",
  lastName: "",
  getFullName: function() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const Choi = {
  firstName: "Hyuno",
  lastName: "Choi",
}

let getFullNameOfChoi = person.getFullName.bind(Choi);
console.log(getFullNameOfChoi()); // Hyuno Choi
  • Choi 객체는 아무런 메소드가 없음.
  • 하지만 person.getFullName 메소드에 Choi를 바인딩하여 Choithis 맥락을 사용할 수 있다.

this 맥락을 유지해야 할 때

const Choi = {
  firstName: "Hyuno",
  lastName: "Choi",
  getFullName: function() {
    return `${this.firstName} ${this.lastName}`;
  }
}

setTimeout(Choi.getFullName, 1000); // undefined undefined
  • 언뜻 예상하면 Hyuno Choi가 출력될 것 같지만 아무것도 출력되지 않음.
  • setTimeOut 함수에 Choi.getFullName 메소드가 콜백으로 전달되는 순간 해당 메소드의 this 맥락이 사라지기 때문.
  • 이때 Choi.getFullName 메소드를 전달해주는 동시에 Choi 객체를 바인딩하면 this 맥락을 유지할 수 있음.
setTimeout(Choi.getFullName.bind(Choi), 1000); // Hyuno Choi

Ref

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions