JQuery、ajax 和 js OOP

JQuery, ajax and js OOP

我有以下代码:

var Foo = function(){
    this._temp="uh";
};

Foo.prototype._handler=function(data, textStatus){
    alert(this._temp);
}

Foo.prototype.run=function(){
    $.ajax({
        url: '....', 
        success: this._handler
    });
}

所以当我朗姆酒时:

new Foo().run();

并且 ajax 查询已返回,处理程序已处理,我收到错误 this._temp is undefined。是什么原因以及如何使用此代码模板修复它?

$.ajax({
    url: '....', 
    success: this._handler.bind(this)
});

您需要绑定函数的上下文。

如果您使用调试器(在 Web 浏览器中可用),您会看到 this 没有引用您的对象实例。