자바스크립트 입문_bind 메소드
자바스크립트 2021. 5. 5. 16:23(본 포스팅은 위키북스의 '코어자바스크립트' 책을 공부하면서 작성되었습니다_내돈내산)
< bind 메소드 >
- bind 메서드: ES5에서 추가된 기능. call과 비슷하지만 즉시 호출하지는 않고, 넘겨받은 this 및 인수들을 바탕으로 새로운 함수를 반환하는 메서드
- bind 메서드의 용도는 함수에 this를 미리 적용하는것 / 부분 적용함수를 구현하는 것 두가지로나뉨.
- 다시 새로운 함수를 호출할 때 인수를 넘기면 그 인수들은 기존 bind 메서드를 호출할 때 전달했던 인수들의 뒤에 이어서 등록됨.
// 일반적인 함수
var func = function (a, b, c, d) {
console.log(this, a, b, c, d);
};
func(1,2,3,4); // window{...} 1 2 3 4
-----------------------------------------------------------------------------------------------
// bind메소드를 이용해 this를 미리 적용시키는 방법
var bindFunc1 = func.bind({x:1});
bindFunc1(5, 6, 7, 8); // {x:1} 5 6 7 8
-----------------------------------------------------------------------------------------------
// bind 메소드를 이용한 부분적용함수 구현
var bindfunc2 = func.bind({x:1}, 4, 5); // 4개의 인자중 2개만 부분적용시킴
bindFunc2(6,7); // {x:1} 4 5 6 7
bindFunc2(8,9); // {x:1} 4 5 8 9
- name 프로퍼티 -
- bind 메서드를 적용해서 새로 만든함수는 name 프로퍼티에 수동태인 'bound' 라는 접두어가 붙음. 코드추적에 사용하면 용이함.
var func = function(a, b, c, d){
console.log(this, a, b, c, d);
};
var bindFunc = func.bind({x:1}, 4, 5);
console.log(func.name); // func
console.log(bindFunc.name); // bound func
- 상위 컨텍스트의 this를 내부함수나 콜백함수에 전달 -
(내부함수에 this전달 - call vs. bind)
// call 메소드 이용
var obj = {
outer: function(){
console.log(this); // obj
var innerFunc = function() {
console.log(this); // window {...}
};
innerFunc.call(this); // 이곳에서 발생하는 this인 obj를 innerFunc로 전달, obj
}
};
obj.outer();
-----------------------------------------------------------------------------------------------
// bind 메소드 이용
var obj = {
outer: function(){
console.log(this); // obj
var innerFunc = function() {
console.log(this); // window {...}
}.bind(this) // 이곳에서 발생하는 this인 obj를 innerFunc로 전달
innerFunc(); // obj
}
};
obj.outer();
( 내부함수에 this 전달-bind메소드)
var obj = {
logThis: function() {
console.log(this);
},
logThisLater1: function() {
setTimeout(this.logThis, 500);
},
logThisLater2: function() {
setTimeout(this.logThis.bind(this), 1000); // this를 bind해서 obj 객체 전체가 달림
},
};
obj.logThisLater1(); // window
obj.logThisLater2(); // obj {logThis:f, ...}
'자바스크립트' 카테고리의 다른 글
자바스크립트 입문_콜백함수(callback function) 개념 (0) | 2021.05.05 |
---|---|
자바스크립트 입문_콜백함수(callback function)내에서 별도의 인자로 this를 받는 경우 (0) | 2021.05.05 |
자바스크립트 입문_명시적 this 바인딩(call, apply 메소드) (0) | 2021.05.05 |
자바스크립트 입문_this (여러가지 상황에 따른) (0) | 2021.05.04 |
자바스크립트 입문_스코프, 스코프체인, outerEnvironmentReference (0) | 2021.05.04 |