Function.prototype.bind(thisArgs[, arg1], arg2[, ...]]);
ES5에서 추가 된 메서드 이다. call과 비슷하지만 바로 실행하지 않고 넘겨받은 this, 인수들을 바탕으로 새로운 함수를 반환하기만 하는 메서드이다.
var func = function(a, b, c, d) {
console.log(this, a, b, c, d);
}
func(1, 2, 3, 4); // Window, 1 2, 3, 4
var bindFunc = func.bind({x:1});
bindFunc(5 ,6 ,7 ,8);
bind 메서드를 적용해서 새로 만든 함수는 name 프로퍼티에 bound(bind 수동태) 라는 접두어가 붙는다.
apply, call 보다 코드를 추적하기 쉽다.
현재 this를 실행할 내부함수나 콜백함수에 call(this) 또는 bind(this) 하면 된다.
var obj = {
outer: function(){
console.log(this);
var innerFunc = function() {
console.log(this);
}
innerFunc.call(this); - (1)
}
}
obj.outer();
(1) - 하게되면 innerFunc 함수에서의 this 는 obj가 된다. 같은 방법으로는 아래와 같이 bind방법이 있다.
outer: function(){
console.log(this);
var innerFunc = function() {
console.log(this);
}.bind(this);
바로 위 예제를 화살표함수로 작성한 것과 같은 this를 가지는 코드이다.
화살표 함수는 this가 없다. 가장 가까운 스코프체인에서 this를 가리킨다.
var obj = {
outer: function(){
console.log(this);
var innerFunc = () => {
console.log(this);
}
innerFunc();
}
obj.outer();
// 여기 콘솔에선 다 obj 출력됨
콜백 함수를 인자로 받는 메서드 중 this를 지정할 객체(thisArgs)를 인자로 지정할 수 있는 경우가 있다. 이러한 thisArg의 값을 지정으로 콜백 함수 내에서의 this 를 마음대로 변경할 수 있다.
var obj = {
sum: 0,
count: 0,
add: function(){
var args = Array.prototype.slice.call(arguments);
args.forEach(function(entry){
this.sum += entry;
++this.count;
}, this);
},
var innerFunc = function() {
console.log(this);
},
}
obj.add(10, 30, 40);
// obj 에 있는 sum , count 들 계산 되서 출력 됨 .
콜백 함수와 함께 thisArg 를 인자로 받는 메서드들은 꽤 많다.