After checking a lot of information, I summarized the following three rules. These three rules can already solve all the problems I have encountered so far.
Rule 0: The function itself is a special type, most time, can be considered as a variable.
function a()
{
alert(this);
}
or
var a = function()
{
alert(this);
}
It can be thought of as creating a variable, and the value of this variable is a function.
Rule 1: If a function is the key value of an object, then this points to this object. This rule is easy to understand:
var a = function(obj)
{
alert(this == obj);
}
var o = {};
o.afun = a;
o.afun(o); //true
The function is a variable, but it can be bound to an object, and this will point to the o object.
It must be noted here that if there is no bound object, this will point to the window object by default.
A few examples:
function a()
{
//this == window
}
function a()
{
//this == window
function b()
{
//this == window
}
}
It must also be noted that binding is not transitive, such as the nested function above, a binding to the o object, then it affects the a function,
and b still points to the window.
Rule 2: If the function new is called, an object will be created, and this points to the newly created object. var o = new a();
At this time, o is no longer a function, but in fact, it can be considered as such a process.
Create an object var o = {};
Then point this to o and initialize o through this.
Rule 3: You can change the pointer of this through apply The binding of this apply is more flexible. In fact, the function of apply is similar to the following function .
var a = function (obj)
{
alert(this == obj);
};
obj.fun = a;
obj.fun(obj);//true
Simple, ok a.apply(obj, [obj]); // true
javascript's this can be simply considered as late binding. When there is no place to bind, window is bound by default. Comprehensive example:
There is a very commonly used function each in jquery, which can bind the looped object elements to this for easy operation.
Here is just a simple demonstration:
Code
function each(tagName, callback)
{
var lists = document.getElementsByTagName(tagName);
for (var i = 0; i < lists.length; i )
{
callback.apply(lists[i]);
}
}
each("a",
function ()
{
this.style. color = "red";
}
);
You can see that all the links in my header navigation have turned red.