javascript对象,回调和这个关键字

时间:2012-01-10 16:55:49

标签: javascript this jquery-callback

我无法弄清楚如何在jquery ajax回调中正确引用'right''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?有更好的方法吗?

4 个答案:

答案 0 :(得分:4)

您可以使用$.ajaxcontext属性:

var foo1 = new Foo();

$.ajax({
  context: foo1,
  success: function(response) { this.onCallback(response); }
});

...这会导致回调中的this引用您的Foo对象。

答案 1 :(得分:2)

你做不到。

你必须写:

$.ajax({
  ...
  success: function(response) { foo1.onCallback(response); ... }
});

或者这个:

myCallback = foo1.onCallback.bind(foo1);

请注意Function.bind()需要ECMAScript 5.

答案 2 :(得分:1)

使用以下习语:

myCallback = foo1.onCallback.bind(foo1);

事实上,您应该进一步利用JavaScript中的一流功能支持:

foo1 = new Foo()

$.ajax({
  ...
  success: foo1.myCallback.bind(foo1)
});

另见:

答案 3 :(得分:-1)

您只需添加语句alert(this);即可查看它是否为foo1。

相关问题