Use of call and apply
1. Passing parameters
The first parameter of call and apply is the object to be bound, the second parameter is different
The parameters used by call are variable parameters
The parameter used by apply is an array
function sum () {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
Result + = Arguments[i];
}
return result;
}
function Obj (x, y) {
this.x = x;
This.y = y;
}
var obj = new obj (10, 20);//This is the way the function is directed to the obj
var result = Sum.call (obj, obj.x, obj.y);
var result2 = sun.apply (obj, [obj.x, Obj.y]);
Console.log (result);
Console.log (RESULT2);
2. Extended scope--determined by the scope range of the bound object
var student = {name: ' Zjy '};
var teacher = {name: ' Mr.zhao '};
function ShowName () {
Console.log (this.name);
}
Showname.call (student);
Showname.call (teacher);
3. Using call,apply to implement inheritance
function Animal () {
This.hoal = function () {
Console.log ("AAA");
}
}
function Cat () {
Animal.call (this);
}
var cat = new Cat ();
Cat.hoal ();
function Tiger () {
Cat.apply (this);
}
var tiger = new Tiger ();
Tiger.hoal ();
4. Simple simulation of call implementation
function sum () {
var result = 0;
for (var i = 0; i < arguments.length; i++) {
Result + = Arguments[i];
}
return result;
}
function Obj (x, y) {
this.x = x;
This.y = y;
}
Simple Call Simulation
Sum.mycall = function (obj) {
if (Arguments.length = = 0) {
Console.log ("must pass in a binding object");
} else {
Return this (Arguments[1], arguments[2]);
}
}
Console.log (Sum.mycall (obj, obj.x, obj.y));
For call and apply can realize the decoupling of code, easy to expand the program.
Use of call and apply