JQuery, ajax and js OOP

JQuery, ajax and js OOP

本文关键字:js OOP and ajax JQuery      更新时间:2024-03-19

我有以下代码:

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没有引用您的对象实例。