Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
soonitoon opened this issue Jan 29, 2023 · 0 comments
Open

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

soonitoon opened this issue Jan 29, 2023 · 0 comments

Comments

@soonitoon
Copy link
Owner

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant