1 <Scripttype= "Text/javascript">2 //Call Method:3 //Syntax: Call (THISOBJ[,ARG1,ARG2,..., ArgN])4 //definition: A method of invoking an object that replaces the current object with another object5 6 //Apply method:7 //syntax: Apply ([Thisobj,argarray])8 //definition: One method of applying an object, replacing the current object with another object9 Ten //A, One functionAdd (A, b) { A Alert (A+b); - } - functionSub (A, b) { the Alert (A-b); - } - Add.call (Sub,3,1); - Replace Sub,add.call with Add (sub,3,1)==Add (3,1), the result is alert (4); + //B, - functionAnimal () { + This. Name="Animal"; A This. ShowName=function(){ at Alert ( This. Name); - } - } - functionCat () { - This. Name="Cat"; - } in varAnimal=NewAnimal (); - varCat=NewCat (); to + Animal.showName.call (cat); - //using the call or Apply method, the ShowName () method that originally belonged to the animal object is given to the object cat. The result is alert ("Cat"); the //c, inheritance can be implemented. * functionAnimal (name) { $ This. Name=name;Panax Notoginseng This. ShowName=function(){ - Alert ( This. Name); the } + } A functionCat (name) { the Animal.call ( This, name); + } - varCat=NewCat ("Black Cat"); $ cat.showname (); $ //Animal.call (this) means that using the Animal object instead of the This object, cat has all the methods and properties of Animal, and the Cat object can invoke the Animal method and properties directly. - //d, multiple inheritance - functionClass10 () { the This. Showsub=function(A, b) { - Alert (A-b);Wuyi } the } - functionClass11 () { Wu This. Showadd=function(A, b) { - Alert (A+b); About } $ } - functionClass2 () { - Class10.call ( This); - Class11.call ( This); A } + //multiple inheritance is achieved with two call. the - the difference between the call and apply is that the second argument to this can be any type, and the second argument of apply must be an array or arguments $ </Script>
Call method and apply method in JS language