Jquery Ajax callback function this points to the problem

Source: Internet
Author: User

For example, if you call an object with this in the global scope, the current object's "this" points to window. Javascript provides two methods to change the direction of this. They are call and apply, and of course there are methods implemented using closures. This article uses an example to illustrate these problems.

First look at a demoCodeThis code is only for demonstration and has no practical significance.

Copy code The Code is as follows: // a socket connection object with no practical significance
VaR socket =
{
Connect: function (host, Port)
{
Alert ('ing ing socket server, host: '+ host +', Port: '+ port );
}
};
// An instant messaging class. The connect method is also called as an Ajax callback function.
Function classim ()
{
This. Host = '192. 168.1.28 ';
This. Port = '123 ';
This. Connect = function (data)
{
Socket. Connect (this. Host, this. Port );
};
}
// Instantiate the instant messaging class
VaR im = new classim ();
// Ajax request. It is assumed that the user's Web login is successful through the Web before the socket connection is enabled.
$. Get ('checkweblogin. aspx ', Im. Connect );
Run the preceding example and you will see that the host and port popped up are all undefined, because the callback function's this is not pointing to the IM object, but the Ajax configuration object ajaxsettings of jquery. In jquery, S. Success is used instead of the incoming callback function for execution, and the success call object is S, which is short for the ajaxsettings object below.

Ajaxsettings:
{
URL: location. href,
Global: True,
Type: "Get ",
Contenttype: "application/X-WWW-form-urlencoded ",
Processdata: True,
Async: True
}

To prove this, you can modify the code and test it. You will see the property names of objects such as URL, global, type, and contenttype:Copy codeThe Code is as follows: This. Connect = function (data)
{
For (var key in this)
{
Alert (key );
}
}

Now that I understand the problem, I will try to solve it. In fact, our purpose is to expect Ajax callback function code socket. connect (this. host, this. port. the CONNECT () method can obtain the correct parameter value. To get the expected Ajax callback function execution results, I analyzed the following methods:

Method 1

Directly pass the correct reference of an object instead of the this pointer, or call it an object. This is the most common practice, that is, to use a variable to store references to the current object during class instantiation, and directly use this variable to replace this in subsequent methods. Note: This method does not actually change the point of this. The Demo code is as follows. Pay attention to the difference between the two codes before and after the comparison. I also highlight the different codes.Copy codeThe Code is as follows: var socket =
{
Connect: function (host, Port)
{
Alert ('ing ing socket server, host: '+ host +', Port: '+ port );
}
};
Function classim ()
{
VaR self = this;
This. Host = '192. 168.1.28 ';
This. Port = '123 ';
This. Connect = function (data)
{
Socket. Connect (self. Host, self. Port );
};
}
VaR im = new classim ();
$. Get ('checkweblogin. aspx ', Im. Connect );

Method 2

Use Apply and closure to truly change the point of this. The following method stores the this object in the function call to a Temporary Variable _ method, and then uses the closure to pass it to the returned function object, use apply in the returned function to replace this of the called object with the target object thisobj. This method is implemented by many JavaScript frameworks, and the following function prototype method is simplified from the prototype framework. Note that I added the apply method to the function prototype first. This apply method is not embedded in the script and is custom. If you like it, you can set individual names.Copy code The Code is as follows :/**
* Changed the jquery Ajax callback function. This Pointer Points
* @ Param {object} thisobj Replace the object of the current this pointer
* @ Return {function} function (data ){}
*/
Function. Prototype. Apply = function (thisobj)
{
VaR _ method = this;
Return function (data)
{
Return _ method. Apply (thisobj, [data]);
};
}
VaR socket =
{
Connect: function (host, Port)
{
Alert ('ing ing socket server, host: '+ host +', Port: '+ port );
}
};
Function classim ()
{
This. Host = '192. 168.1.28 ';
This. Port = '123 ';
This. Connect = function (data)
{
Socket. Connect (this. Host, this. Port );
};
}
VaR im = new classim ();
$. Get ('checkweblogin. aspx ', Im. Connect. Apply (IM ));

method 3

call the actual callback handler in the anonymous callback function. This method can solve the same problem, but the code is too long and redundant. We do not recommend this in actual development. This method ensures the object that calls the connect method or the IM object, so as to ensure that this points to or IM object. The Code is as follows: copy Code the code is as follows: $. get ('checkweblogin. aspx ', function (data) {im. connect (data)});

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.