I. Definition of a method
Call Method:
Syntax: Call (Thisobj,object)
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.
code example:
1 function Animal (name) {2 this.name = name; 3 this.showname = function () {4 console.log (this.name); 5 } ; 6} 7 8 function Cat (name) {9 animal.call (this, name),}11 cat.prototype = new Animal (), function Dog (name { animal.apply (this, name),}16 dog.prototype = new Animal (), + var cat = new Cat ("Black cat");//call must be Obje ct19 var dog = new Dog (["Black Dog"]); Apply must be Array21 cat.showname (), Dog.showname (), Console.log (cat instanceof Animal), and Console.log (dog Instanceof Animal);
Analog call, the this replacement of apply
1 function Animal (name) {2 this.name = name; 3 this.showname = function () {4 alert (this.name); 5 }; 6}; 7 8 function Cat (name) {9 this.superclass = animal;10 this.superclass (name); Delete Superclass;12} var cat = new Cat ("Black cat"); Cat.showname ();
The difference between call and apply