This working principle
If a function is called as an object method, this will be assigned to this object.
Copy code code as follows:
var Parent = {
Method: FUNCTION () {
console.log (this);
}
};
parent.method ();
// <-Parent
Note that this behavior is very "fragile". If you get a reference and call a method, the value of this will not be Parent, but the global object of Window. This confuses most developers.
Copy code code as follows:
ThisClowncar ();
// <-window
Change this
The .call, .apply, and .BIND methods were used to operate the method of calling functions to help us define the values of this and the parameter values passed to the function.
Function.prototype.call can have any number of parameters. The first parameter is assigned to this, and the rest is passed to the call function.
Copy code code as follows:
Array.prototype.slice.call ([1, 2, 3], 1, 2)
// <- [2]
Function.prototype.apply is similar to .call, but the parameters it passed to the function is an array, not any parameter.
String.prototype.split.apply ('13.12.02 ', ['. '])
// <- ['13', '12', '02']
Function.prototype.bind creates a special function that will always use parameters passed to .Bind as a value that can be passed to .Bind, and the Curride version that can allocate part of the parameters and create the original function.
Copy code code as follows:
var arr = [1, 2];
var add = array.prototype.push.bind (Arr, 3);
// Effectively The Same as arr.push (3)
add ();
// Effectively The Same as arr.push (3, 4)
add (4);
console.log (ARR);
// <- [1, 2, 3, 3, 4]
This in the domain chain
In the following example, this will not be able to remain unchanged in the domain chain. This is the defect of the rules, and it often brings confusion to amateur developers.
Copy code code as follows:
Function scoping () {
console.log (this);
Return function () {
console.log (this);
};
}
scoping () ();
// <-window
// <-window
There is a common method to create a local variable to maintain a reference to this, and there must be no life variables in the sub -action domain. The variables of the same name in the sub -scope will cover the reference to this in the parent score. http://www.cnblogs.com/sosoft/
Copy code code as follows:
function retaining () {
var seelf = this;
Return function () {
console.log (self);
};
}
Retaining () ();
// <-window
Unless you really want to use the This of the parent scope at the same time and the current This value, because of some inexplicable reasons, I prefer to use the method .Bind function. This can be used to specify the parent scope to designate the sub -scope.
Copy code code as follows:
function up () {) {)
Return function () {
console.log (this);
} .Bind (this);
}
break () ();
// <-window