For example, if an object containing this is called in the global scope, this of the current object points to window. In order to make the point of this conform to your own wishes, JavaScript provides two methods to change the point of this, which are call and apply. Of course, there are also methods that use closures to achieve this. This article illustrates these issues through an example.
Let’s look at a demo code first. This code is for demonstration purposes only and has no practical significance.
//A socket connection with no practical meaning 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 called 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);
};
}
//Instantiate the instant messaging class
var IM = new classIm();
//AJAX request, here it is assumed that to open the socket connection, you must first know through the WEB that the user's WEB login is successful
$.get('CheckWebLogin.aspx', IM.connect);
Run the above example, you will see that the pop-up host and port are both undefined. That is because this of the callback function does not point to the IM object, but to the IM object. Is jQuery's AJAX configuration object ajaxSettings. Inside jQuery, s.success is used instead of the incoming callback function to execute, and the calling object of success is s, which is the abbreviation of 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 like this to test it, you will see the url, Attribute names of global, type, contentType and other objects:
this .connect = function(data)
{
for (var key in this)
{
alert(key);
}
}
Now that we understand the problem, let’s find a way to solve it. In fact, our purpose is to hope that this in the AJAX callback function code socket.connect(this.host, this.port) points to the instance object IM of classIm, or that the socket.connect() method can get the correct parameter value. . In order to get the expected execution result of the AJAX callback function, I analyzed the following methods:
Method 1
Directly pass the correct reference of the object instead of this pointer , or called object transfer. This is the most common approach, that is, using a variable to store a reference to the current object when the class is instantiated, and using this variable directly in subsequent methods instead of using this. Note: This method does not actually change what this points to. The demo code is as follows. Pay attention to the difference between the two codes before and after. I also highlight the different parts of the code.
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 2 Use apply and closure to truly change the direction of this. The following method stores the this object when the function is called into a temporary variable _method, and then uses a closure to pass it to the returned function object. In the returned function, use apply to replace the this object of the calling object with the target object thisObj. . This method is the practice of many JavaScript frameworks, and the Function prototype method below is what I simplified from the prototype framework. Note that I first added the Apply method to the Function prototype. This Apply is not the script's built-in apply. It is customized by me. You can give it a different name if you like.
/**
* Change the jQuery AJAX callback function this pointer to point to
* @param {Object} thisObj The object 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 3
Call the actual callback processing function in the anonymous callback function. Although this method can solve the same problem, the code is a bit long and redundant. This is not recommended in actual development. This method ensures that the object calling the connect method is still an IM object, thus ensuring that this points to an IM object. The code is as follows:
$.get('CheckWebLogin.aspx' , function(data){IM.connect(data)});