简体   繁体   English

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

[英]javascript objects, callback and this keyword

I'm having trouble figuring out how to correctly reference the 'right' 'this' in a jquery ajax callback. 我在查找如何在jquery ajax回调中正确引用'right''this'时遇到了麻烦。

I have a javascript class where I define the callback: 我有一个javascript类,我定义了回调:

Foo.prototype.onCallback = function(response) {
  // 'this' should refer to an instance of foo in both the following cases
  this.bar(...)    
  this.hello(...)
}

outside of the class I have: 在课外我有:

foo1 = new Foo()
myCallback = foo1.onCallback;

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

Right now I believe 'this' within foo1.onCallback is referring to the html element the ajax call is attached to. 现在我相信foo1.onCallback中的'this'指的是附加ajax调用的html元素。 How do I ensure that 'this' refers to foo1? 我如何确保'this'指的是foo1? Is there a better way to do this? 有一个更好的方法吗?

You could use the context property of $.ajax : 您可以使用$.ajaxcontext属性:

var foo1 = new Foo();

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

...which causes this in the callback to reference your Foo object. ...导致回调中的this引用你的Foo对象。

You can't do that. 你不能这样做。

You must either write: 你必须写:

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

or this: 或这个:

myCallback = foo1.onCallback.bind(foo1);

Note that Function.bind() requires ECMAScript 5. 请注意, Function.bind()需要ECMAScript 5。

Use the following idiom: 使用以下习语:

myCallback = foo1.onCallback.bind(foo1);

In fact you should take advantage of first-class function support in JavaScript even further: 实际上你应该进一步利用JavaScript中的一流功能支持:

foo1 = new Foo()

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

See also: 也可以看看:

You could simply add the statement alert(this); 你可以简单地添加语句alert(this); to see the if it is foo1. 看看它是不是foo1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM