1. Common examples
function Add (A, b) {
alert (A+B);
}
function Sub (A, b) {
Alert (A-B);
}
Add.call (sub,4,3); equivalent to add (4,2);
2. Change the role
function Animal () {
This.name= "Animal";
This.showname=function () {
alert (this.name);
}
}
function Cat () {
This.name= "Cat";
}
var animal=new animal ();
var cat=new cat ();
By using the call or Apply method, the ShowName () method that originally belonged to the animal object is given to the object cat, even though the cat has the same name ShowName method does not execute.
Animal.showName.call (Cat, ",") = = animal.showName.apply (cat,[]); The output is Cat
3. Implementing inheritance
function Animal (name) {
This.name=name;
This.showname= function () {
alert (this.name);
}
}
function Cat (name) {
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.
Animal.call (this, name);
}
var cat = new Cat ("Black cat");
Cat.showname ();
4. Multiple inheritance
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);
}
Call () and apply () in
JS