我无法弄清楚如何在 jquery ajax 回调中正确引用“正确”“this”。
我有一个 javascript 类,我在其中定义回调:
Foo.prototype.onCallback = function(response) {
// 'this' should refer to an instance of foo in both the following cases
this.bar(...)
this.hello(...)
}
在课堂之外我有:
foo1 = new Foo()
myCallback = foo1.onCallback;
$.ajax({
...
success: function(response) {myCallback(response); ... }
});
现在我相信 foo1.onCallback 中的“this”指的是 ajax 调用附加到的 html 元素。如何确保“this”指的是 foo1?有一个更好的方法吗?