하드 말로 설명하지만, 여기에 내가 자주 내 코드가 무엇을 할 :콜백에서이 참조를 유지하는 방법이 있습니까?
var self_reference;
self_reference = this;
$(selector).bind('event', function() {
self_reference.someFunction();
});
임시 변수의 필요없이 (여기 self_reference를) 것을을 작성하는 방법이 있나요?
하드 말로 설명하지만, 여기에 내가 자주 내 코드가 무엇을 할 :콜백에서이 참조를 유지하는 방법이 있습니까?
var self_reference;
self_reference = this;
$(selector).bind('event', function() {
self_reference.someFunction();
});
임시 변수의 필요없이 (여기 self_reference를) 것을을 작성하는 방법이 있나요?
아니요, 없습니다.
this
은 상황에 맞는 것으로서 this
은 콜백 함수 내에서 다른 개체가됩니다. 어딘가에 복사하지 않으면 잃어 버리게됩니다.
jQuery proxy 함수를 살펴볼 수 있습니다.
$.getJSON(url, $.proxy(function()
{
// this has now got the desired context
}, this));
$(selector).bind('event', (function() {
this.someFunction();
}).bind(this));
Function.prototype.bind
는 함수에 ES5 확장이다.
_.bind
을 크로스 브라우저로 사용하거나 $.proxy
을 사용할 수 있습니다.
$(selector).bind('event', (_.bind(function() {
this.someFunction();
}, this));
$(selector).bind('event', ($.proxy(function() {
this.someFunction();
}, this));
는'call'이 좋지 않습니다 - 당신은 호출시에 값을 전달할 수 있고, 당신이 임시 변수에 복사하지 않는 경우가 손실됩니다. jQuery의 프록시는 임시 변수를 효과적으로 만드는 래퍼라고 가정합니다. – Quentin
좋은 지적 - 편집하겠습니다. –