Javascript jQuery回调和原型继承
我创建了以下类:Javascript jQuery回调和原型继承,javascript,jquery,prototype-programming,Javascript,Jquery,Prototype Programming,我创建了以下类: 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 ca
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)的引用已丢失。我怎样才能取回它?我知道我可以在AJAX回调中将ref传递给this
,如下所示:
$.ajax ( { url: 'test.html' } ).done ( function ( source ) {
self.build ( source, self );
} );
但我真的不喜欢它,因为我觉得一个方法永远不应该失去对其对象的引用
有什么想法/建议吗?:) 您可以使用创建跨平台解决方案
APP.core.View = function () {
$.ajax({
url: 'test.html'
}).done($.proxy(this.build, this));
return this;
};
对于现代浏览器,您可以使用
我刚刚在jQueryAjax文档中找到了另一个答案。ajax函数提供了一个
context
参数,用于指定回调上下文。例如:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});
资料来源:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$( this ).addClass( "done" );
});