来自Ajax回调的Javascript(原型)方法调用

Sub*_* S. 3 javascript ajax jquery

我已经编写了一些面向对象的Javascript,如下所示:

function MyClass(){

    this.SomeFunc(arg1){
        result = <some processing on arg1>;
        return result;
    };

    this.SomeOtherFunc(){
        return $.ajax({
            <some restful call>
        }).done(function(){
            var localvar = this.SomeFunc(<value obtained by restful call>);
            <some operations with localvar>;
        });
    };
};

var myObj = new MyClass();
myObj.SomeOtherFunc();
Run Code Online (Sandbox Code Playgroud)

而且我在Web控制台中收到一个错误:“ this.SomeFunc不是函数”。如果直接在函数中调用它,就没有问题。调用仅在Ajax内部失败。进行此函数调用的正确方法是什么?

Sud*_*oti 5

this您的回调函数中的this引用不同于SomeFunc,请尝试执行以下操作:

this.SomeOtherFunc(){
    var thatFunc = this; //get hold of this
    return $.ajax({
        <some restful call>
    }).done(function(){
        var localvar = thatFunc.SomeFunc(<value obtained by restful call>);
        <some operations with localvar>;
    });
};
Run Code Online (Sandbox Code Playgroud)