1. Method definition
Call Method:
Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Definition: Invokes one method of an object, replacing the current object with another object.
Description
The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj.
If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
Apply method:
Syntax: Apply ([Thisobj[,argarray]])
Definition: A method of applying an object that replaces the current object with another object.
Description
If Argarray is not a valid array or is not a arguments object, it will result in a TypeError.
If none of the Argarray and Thisobj parameters are provided, then the Global object is used as a thisobj and cannot be passed any parameters.
2. Common examples
Instance A:
functionAnimal () { This. Name = "Animal"; This. ShowName =function() {alert ( This. Name); } } functionCat () { This. Name = "Cat"; } varAnimal =NewAnimal (); varCat =NewCat (); //using the call or Apply method, the ShowName () method that originally belonged to the animal object is given to the object cat. //The input result is "Cat"Animal.showName.call (Cat, ","); //animal.showName.apply (cat,[]);
Call means to put the animal method on the cat, the original cat is no ShowName () method, now is to put animal showname () method on the cat to execute, so this.name should be cat
Instance B: Implementing inheritance
function Animal (name) { this. Name = name; This function () { alert (this. Name); } } function Cat (name) { Animal.call (this, name); } var New Cat ("Black cat"); Cat.showname ();
Animal.call (this) means that the Animal object is used instead of the this object, so there is no Animal of all the properties and methods in Cat, and the Cat object can directly invoke the Animal method and properties.
Instance C: Multiple inheritance
function Class10 () { thisfunction(b) { alert (a-b); }} function Class11 () { thisfunction(b) { alert (a+b); }} function Class2 () { Class10.call (this); Class11.call (this);}
It is simple to use two call to achieve multiple inheritance. Of course, JS inheritance There are other methods, such as the use of the prototype chain, this is not part of the scope of this article, just to illustrate the use of call. Said call, of course, and apply, these two methods are basically a meaning, the difference is that the second parameter of call can be any type, and the second argument of apply must be an array, or it can be arguments
Call () and the Apply () method in JavaScript to implement inheritance