在jquery中将对象传递给回调函数

san*_*eev 1 javascript ajax jquery

我最近正在研究小型聊天模块,它需要不断检查服务器是否有新消息.

我正在向服务器发送ajax请求,服务器保持连接,直到找到新消息(长轮询).

代码:

var chatController = function(){

//other variable declaration

/**
*  Ajax call to monitor the new message , on complete of ajax call sending other call
*/

this.checkNewMessage = function(){
  console.log(this); // placed this for debugging purpose
       $.ajax({
         url : SITEURL.CHECK_MESSAGE,
         data : this.currrentUserDetails,
         dataType : 'json' ,
         cache    : false,
         success  :(function(obj){
            //temp = obj;
            return obj.parseNewMessageResponse;
         })(this),
         complete: (function(obj){
            //temp = obj;
            return obj.checkNewMessage;
         })(this),  
       });


};

  // other function and variable

});
Run Code Online (Sandbox Code Playgroud)

当我试着打电话的时候

var mainController = new chatController();
mainController.checkNewMessage();
Run Code Online (Sandbox Code Playgroud)

问题

我认为我能够向服务器发送连续的单个请求,但令我惊讶的是我只能一个接一个地发送2个a​​jax请求.

我的调试

当我试图调试时,我追溯到第一个调用this对象被传递指向chatController

         complete: (function(obj){
            return obj.checkNewMessage;
         })(this),     // this here point to chatController object
Run Code Online (Sandbox Code Playgroud)

第二次this传递对象指向ajax object

         complete: (function(obj){
            return obj.checkNewMessage;
         })(this),     // this here point to ajax object
Run Code Online (Sandbox Code Playgroud)

我使用JavaScript闭包将chatController对象传递给completejquery的参数

所以我想要的是将参数传递给jQuery complete函数的方式,以便它指向我的原始参考

rnr*_*ies 6

有各种可行的解决方案

你可以使用$.proxy:

在我看来,最好的做法.

$.ajax({
    //...
    success: $.proxy(function(json) {
         // `this` refers to the second argument of `$.proxy`
    }, this)
});
Run Code Online (Sandbox Code Playgroud)

您可以设置context选项:

$.ajax({
    //...
    context: this,
    success: function(json) {
         // `this` refers to the value of `context`
    }
});
Run Code Online (Sandbox Code Playgroud)

或者使用一个闭包:

var self = this;
$.ajax({
    //...
    success: function(json) {
         // `this` refers to ajax request, use self instead
         $(self).dosomething();
    }
});
Run Code Online (Sandbox Code Playgroud)