The authoritative guide says that call and apply can be treated as a method of an object by invoking the form of a method
Calling functions indirectly: functions called by call and apply: The specific usage---is as follows:
1. Call usage first, call can receive two parameters, or it may not be two; The first argument is the one to invoke the function.
A parent object that obtains a reference to it through this in the body of the function;
function A () {
Console.log (this); The This object in output function a
}
Function B () {}//define functions B
var obj = {name: ' Onepixel '}; Define Object obj
Call
A ();//this represents the Window object;
a.call;//itself is a function method//window
Console.log (A.call); function call () {[native code]};
A.call (NULL); Window passed in null, this in function, point to Window
A.call (undefined);//window incoming undefined, this in function, point to Window
A.call (1); Number passed in numeric type, this points to the corresponding wrapper type
A.call ("); String to pass in strings, this pointer to string type
A.call (TRUE); Boolean Incoming Boolean type, this pointer to Boolean type
A.call (b);//function B () {}
A.call (obj); Object points to obj;
Use of call;
You can see what parameter the first parameter in call () is in, and this points to the corresponding package type;
When the parameter is null,undefined, this points to the window;
Specific usage:
Use of call;
var m = {
Name: ' Onepixel ',
Say:function () {
Console.log (' hi,i am function m! ');
},
}
function n (name) {
Console.log (' Post params: ' +name);
Console.log (' I am ' +this.name);
This.say;
}
N.call (M, ' test ');//post params:test
I am onepixel
I ' m function A! Do not know why did not call;
In other words, n can invoke the method in M through call;
About Appply
The only difference between apply and call is that the second parameter is passed differently,
The second argument to apply must be an array, and call allows a list of arguments to be passed
It is worth noting that while apply receives a parameter array, it is passed to the calling function,
is passed in the form of a parameter list
function f (x, Y, z) {
Console.log (x, Y, z)
}
F.apply (undefined,[1,2,3]);//1,2,3
The first argument is passed null or undedined points to window
Focus://js in the concept of inheritance, call and apply can be achieved;
function Animal (name,weight) {
THIS.name = name;
This.weight = weight;
}
function Cat () {
Animal.call (this, ' cat ', ' 50 ');
Animal.apply (this,[' cat ', ' 50 ');
This.say = function () {
Console.log (' I am ' +this.name+ ' myweight ' +this.weight)
}
}
var cat = new Cat ();
Cat.say ();
This piece of code to understand ....
About Call and apply