call and apply methods The call method can change the context this pointer. Similar methods include apply, which is mainly used when various methods of js objects call each other to keep the current this instance pointer consistent, or in In special cases, the this pointer needs to be changed.
obj1.method1.call(obj2,argument1,argument2)
As above, the function of call is to put the method of obj1 on obj2 for use, and the following argument1...these are passed in as parameters.
Give a specific example
function add(a , b) {
alert(a b);
}
function sub(a, b) {
alert(a - b);
}
add.call(sub, 3, 1);
What this example means is to replace sub with add, add.call(sub,3,1) == add(3,1), so the running result is: alert(4); // Note: Functions in js are actually objects, and the function name is a reference to the Function object.
Look at a slightly more complicated example
function Class1 () {
this.name = "class1";
this.showNam = function() {
alert(this.name);
}
}
function Class2() {
this.name = "class2";
}
var c1 = new Class1();
var c2 = new Class2();
c1.showNam.call(c2);
Note that call means to put the method of c1 on c2 for execution. Originally, c2 did not have a showNam() method. Now it is to put the method of c1 The showNam() method is placed on c2 for execution, so this.name should be class2, and the execution result is: alert ("class2");
In addition, call can be used to implement inheritance
function Class1() {
this.showTxt = function(txt) {
alert (txt);
}
}
function Class2() {
Class1.call(this);
}
var c2 = new Class2() ;
c2.showTxt("cc");
In this way, Class2 inherits Class1. Class1.call(this) means using the Class1 object instead of this object, then Class2 Doesn't it have all the properties and methods of Class1? The c2 object can directly call the methods and properties of Class1. The execution result is: alert ("cc");
This is how javaScript simulates object-oriented Inherited, multiple inheritance can also be achieved.
function Class10() {
this.showSub = function(a, b) {
alert(a - b);
}
}
function Class11() {
this.showAdd = function(a, b) {
alert(a b);
}
}
function Class2() {
Class10.call(this);
Class11.call(this);
}
1.call method
Calls a method of an object to replace the current object with another object.
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Parameters
thisObj optional. The object that will be used as the current object.
arg1, arg2, , argN optional. A sequence of method parameters will be passed.
2.apply method
Apply a method of a certain object and replace the current object with another object.
apply([thisObj[,argArray]])
Parameters
thisObj Optional. The object that will be used as the current object.
argArray Optional. Array of arguments that will be passed to this function.
The difference between the two:
The functions implemented by the two are exactly the same, but the parameter passing method is different. Call separates each parameter with a comma (,). And apply is to pass all parameters into an array.