In the Web front-end development process, we often need to change this point, usually we think of the call method, but for call understanding many people are not very clear, then the following small series to give you a detailed talk of call and apply detailed knowledge
I. Definition of the Call method
Everyone in Baidu can search call, the definition of call is very clumsy. In my understanding, A.call (B,arg1,arg2 ...) Is the method of a object applied to the B object. For example, the following example:
| The code is as follows |
Copy Code |
function Add (a,b) { alert (A+B); } function reduce (A,B) { alert (a-b); } Add.call (reduce,1,3)//Apply the Add method to reduce with a result of 4 |
Two. Call can change this point
The following example:
| The code is as follows |
Copy Code |
Function B () { Alert (This) } b (); Window B.call (); Window B.call ("A", 2, 3); A |
Let's look at a complex example:
| The code is as follows |
Copy Code |
function Animal () { This.name= "Animal"; This.showname=function () { Alert (this.name) } } function Cat () { This.name= "Cat"; } var animal = new animal (); var cat = new Cat (); Animal.showname (); The result is animal Animal.showName.call (CAT); The original cat had no ShowName method, but the animal ShowName method was applied to cat by the call method, so the result was cat |
Third, the implementation of inheritance
The following example:
| The code is as follows |
Copy Code |
function Animal (name) { This.name=name; This.showname=function () { Alert (this.name) } } function Cat (name) { Animal.call (This,name); Animal is applied to cat, so cat has all the properties and methods of animal } var cat = new Cat ("Black Cat"); Cat.showname (); Browser pops Black Cat |
Four. Apply Usage
There is only one place where apply and call are different, except that the other places are basically the same.
A.call (B,arg1,arg2 ...)
Apply (B,[ARG1,ARG2])//apply has only 2 parameters, which will call the argument (Arg1,arg2 ...). is placed in an array as the second parameter of the Apply