함수 메소드 call, apply, bind는 첫번째 매개 변수로 this 값을 명시적으로 지정할 수 있다는 공통점이 있다.
단, bind는 call, apply와 달리 새로운 함수를 반환한다는 특징이 있다.
변수 할당 후 재호출, setTimeout 적용하여 사용할 수 있다.
사라진 'this'
let user = {
firstName: "Irene",
sayHi() {
alert(`Hello ${this.firstName}`);
}
}
setTimeout(user.sayHi, 1000); // Hello undefined
setTimeout 메서드는 인수로 전달받은 함수를 호출할 때 this에 window를 할당한다.
따라서 위 예시의 this.firstName은 window.firstName이 되는데 winodw 객체엔 firstName이 없으므로 undefined가 출력된다. 이렇게 메서드를 전달할 때, 컨텍스트도 제대로 유지하려면 bind를 이용할 수 있다.
setTimeout(user.sayHi.bind(user),1000)
또 다른 예시로는 아래와 같이 사용할 수 있다.
function askPassword(ok, fail) {
let password = prompt("비밀번호를 입력해주세요.", '');
if (password == "rockstar") ok();
else fail();
}
let user = {
name: 'John',
loginOk() {
alert(`${this.name}님이 로그인하였습니다.`);
},
loginFail() {
alert(`${this.name}님이 로그인에 실패하였습니다.`);
},
};
askPassword(user.loginOk.bind(user), user.loginFail.bind(user));
'자바스크립트' 카테고리의 다른 글
How to avoid repeating addEventListener? (0) | 2021.11.24 |
---|---|
Jquery UI draggable creates a whitespace (0) | 2021.11.05 |
modal popup 구현 (0) | 2021.09.06 |
script 태그의 async와 defer 속성 (0) | 2021.08.26 |
Javascript’s __proto__ vs prototype (0) | 2021.06.28 |