Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript jQuery回调和原型继承_Javascript_Jquery_Prototype Programming - Fatal编程技术网

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" );
});