JQuery Ajax callback function This points to the problem _javascript tips

Source: Internet
Author: User
Tags closure function prototype
If you call an object with this in the global scope, the current object's this is pointing to window. In order for this to point to its own intent, JavaScript provides two ways to change the point of this, which is call and apply, and of course, a method that is implemented using closures. This article is an example to illustrate these problems.

Take a look at the demo code, which is for demonstration purposes only and has no practical meaning.

Copy Code code as follows:

//A meaningless socket connection object
var socket =
{
Connect:function (host, Port
{
alert (' Connecting socket Server,host: ' + host + ', Port: ' + Port ');
}
};
//An Instant Messaging class in which the Connect method will also be invoked as an AJAX callback function
function Classim ()
{
This.host = ' 192.168.1.28 ';
This.port = ' 8080 ';
This.connect = function (data)
{
Socket.connect (this.host, This.port);
};
}
//materialized Instant Messaging class
var IM = new Classim ();
//ajax request, where it is assumed that to open the socket connection you first know that the user's Web login succeeded
$.get (' checkweblogin.aspx ', im.connect);
Running the example above, you will see that the popup host and port are undefined, because this is not a pointer to Im object, but jquery's Ajax configuration Object ajaxsettings. Within jquery, the s.success is used instead of the incoming callback function, and the success invocation object is S, which is the abbreviation for the Ajaxsettings object below.

Ajaxsettings:
{
Url:location.href,
Global:true,
Type: "Get",
ContentType: "Appli Cation/x-www-form-urlencoded ",
Processdata:true,
Async:true
}

To prove this, you can modify the code to test it, and you will see the name of the property of the URL, global, type, ContentType object:
Copy Code code as follows:

This.connect = function (data)
{
for (var key in this)
{
alert (key);
}
}


Now that we know what the problem is, we'll find a way to solve the problem. In fact, our goal is to expect Ajax callback function code Socket.connect (This.host, This.port) to point to the class Classim instance object IM, or to Socket.connect () Method can get the correct parameter value. To get the results of the expected Ajax callback function, I analyzed the following methods:

Method One

The correct reference to the object is passed directly, not the this pointer, or the object is called. This is the most common practice of storing a reference to the current object with a variable in a class instantiation, using this variable directly in the later method instead of this. Note: This method does not really change the point of this. The demo code is as follows, notice the difference between before and after two times code, I also highlighted the difference part of the code.
Copy Code code as follows:

var socket =
{
Connect:function (host, Port)
{
alert (' Connecting socket Server,host: ' + host + ', Port: ' + Port ');
}
};
function Classim ()
{
var self = this;
This.host = ' 192.168.1.28 ';
This.port = ' 8080 ';
This.connect = function (data)
{
Socket.connect (Self.host, Self.port);
};
}
var IM = new Classim ();
$.get (' checkweblogin.aspx ', im.connect);

Method Two

Use the Apply plus closure implementation to really change the point of this. The following method saves 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, which in this returned function uses apply to replace this object with the target object thisobj. This approach is the practice of many JavaScript frameworks, and the following function prototyping approach is what I've streamlined from the prototype framework. Notice that I first added the Apply method to the function prototype, which is not a script-built apply, and is my custom, if you like, you can set individual names.
Copy Code code as follows:

/**
* Change jquery Ajax callback function this pointer points to
* @param {Object} thisobj objects to replace 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 (' Connecting socket Server,host: ' + host + ', Port: ' + Port ');
}
};
function Classim ()
{
This.host = ' 192.168.1.28 ';
This.port = ' 8080 ';
This.connect = function (data)
{
Socket.connect (This.host, This.port);
};
}
var IM = new Classim ();
$.get (' checkweblogin.aspx ', IM.connect.Apply (IM));

Method Three

The actual callback handler function is invoked in the anonymous callback function. Although this method can solve the same problem, but the code is a bit long and redundant, in actual development is not recommended to do so. This approach is to ensure that the object or IM object that calls the Connect method is guaranteed to be the this point or Im object. The code is as follows:
Copy Code code 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.