我写了一些像这样的面向对象的 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();
而且我在 Web 控制台中收到错误消息:“this.SomeFunc 不是函数”。如果我直接在一个函数中调用它,就没有问题。调用仅在 Ajax 内部失败。进行此函数调用的正确方法是什么?
最佳答案
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>;
});
};
关于来自 ajax 回调的 Javascript(原型(prototype))方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18696411/