JQueryAJAX callback function this points to question _ javascript skills

Source: Internet
Author: User
Anyone familiar with JavaScript knows that this in JavaScript does not always point to the current object. this in a function or class is closely related to the object that calls this function and the context environment. 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.

Let's take a look at the Demo code. This code is only for demonstration and has no practical significance.

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:

The 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.

The 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.

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:

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.