我创建以下类:
APP.core.View = function () {
var self = this;
$.ajax ( { url: 'test.html' } ).done ( self.build );
return self;
};
APP.core.View.prototype.build = function ( source ) {
var self = this;
// this refers to the AJAX callback.
return self;
};
如您所见,该build
方法的引用this
(属于APP.core.View的引用)已丢失。我如何找回它?我知道我可以this
像这样在AJAX回调中传递ref到:
$.ajax ( { url: 'test.html' } ).done ( function ( source ) {
self.build ( source, self );
} );
但是我真的不喜欢它,因为我觉得方法永远都不要松开对其对象的引用。
有任何想法/建议吗?:)
您可以使用$ .proxy()创建跨平台解决方案
APP.core.View = function () {
$.ajax({
url: 'test.html'
}).done($.proxy(this.build, this));
return this;
};
对于现代浏览器,可以使用.bind()
APP.core.View = function () {
$.ajax({
url: 'test.html'
}).done(this.build.bind(this));
return this;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句