나는 .call
, .apply
및 .bind
으로 생각되지만, 아마도 가장 적은 호출이 사용되지만 기능의 범위를 변경하는 데는 모두 3 가지 방법이 사용됩니다.
내 생각에 .bind
은 강제 범위가있는 함수를 반환하기 때문에 가장 유용합니다. .call
과 .apply
은 즉시 함수를 실행합니다.
개체의 범위를 유지하면서 특정 메서드를 이벤트 처리기로 사용하려면 bind를 사용해야합니다. 그렇지 않으면 범위가 이벤트를 바인딩 할 요소로 변경됩니다.
var singleton = {
prop: 'howdy do!',
method: function() {
this.doSomething();
},
doSomething: function() {
console.log(this.prop);
}
};
$('#thing').on('click',singleton.method.bind(singleton));
단일 배열을 인수 집합으로 변환하는 데 가장 일반적으로 사용됩니다.
var args = ['one', 2, false];
var singleton = {
setStuff: function(place, index, isSomething) {
this.place = place;
this.index = index;
this.isSomething = isSomething;
}
};
singleton.setStuff.apply(singleton, args);
.call
는 일반적으로 그들은 일반적으로 사용할 수없는 것입니다 특정 프로토 타입을 방법을 활용하는 데 사용됩니다.
function myFunc() {
// arguments isn't an array, so it doesn't have access to slice
// however, by scoping the slice method to arguments, we can still use it
var args = Array.prototype.slice.call(arguments, 0);
singleton.setStuff.apply(singleton, args);
}
이 함수가'this'의 값을 특정 것으로 기대할 때. 예를 들어 jQuery 이벤트 핸들러가 있습니다. 네이티브 이벤트 핸들러를 모방 한 특정 콜백을 생성합니다.이 경우 'this'는이 이벤트를 트리거 한 요소로 설정됩니다 – Ian