After looking at a lot of data, I summarized the following three rules, these three rules, have been able to solve all the problems I have encountered at present.
Rule 0: The function itself is a special type, most of the time, it can be considered a variable.
Copy Code code as follows:
function A ()
{
alert (this);
}
Or
var a = function ()
{
alert (this);
}
You can think of creating a variable, and the value of that variable is a function.
Rule 1: If a function is the key value of an object, then this points to the object.
This rule is well understood:
Copy Code code as follows:
var a = function (obj)
{
Alert (This = = obj);
}
var o = {};
O.afun = A;
O.afun (o); True
A function is a variable, but it can be bound to the bottom of an object, and this will point to the O object.
It must be noted here that there is no bound object, the default this is to point to the Window object.
Give a few examples:
Copy Code code as follows:
function A ()
{
this = = window
}
function A ()
{
this = = window
Function B ()
{
this = = window
}
}
It must also be noted that the binding is not transitive, such as the nested function above, a bound to O object, then it affects the a function,
and b is still pointing to window.
Rule 2: If the function is new, an object is created, and this points to the newly created object.
var o = new A ();
This time, O is no longer a function, and actually, it can be considered a process like this.
Create an object var o = {};
Then, point this to O and initialize it with this O.
Rule 3: By apply you can change the point of this
This apply binding is more flexible, in fact, the function of the apply is similar to the following functions.
Copy Code code as follows:
var a = function (obj)
{
Alert (This = = obj);
};
Obj.fun = A;
Obj.fun (obj);//true
Simple, can a.apply (obj, [obj]); True
JavaScript's This can be simply considered late binding, and there is no place to bind when the default binding window.
General Examples:
jquery has a very common function of each, you can bind the loop object elements to this, easy to operate.
Here's a simple demo:
Code
Copy Code code as follows:
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";
}
);
I can see the links to my head navigation turned red.