Call and apply in Javascript
1. Definition of the call Method
You can search for call in Baidu. The definition of call is very easy. In my understanding, a. call (B, arg1, arg2.) is the method of object a applied to object B. For example:
The Code is as follows: |
|
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. The result is 4. |
2. call can change this point
For example:
The Code is as follows: |
|
Function B () { Alert (this) } B (); // window B. call (); // window B. call ("a", 2, 3); // |
Let's look at a complicated example:
The Code is as follows: |
|
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 has no showName method, but the showName method of animal is applied to cat through the call method. Therefore, the result is cat |
3. Implement inheritance
Example:
The Code is as follows: |
|
Function Animal (name) { This. name = name; This. showName = function () { Alert (this. name) } } Function Cat (name) { Animal. call (this, name); // apply Animal to Cat, so Cat has all attributes and methods of Animal. } Var cat = new Cat ("Black Cat "); Cat. showName (); // Black Cat is displayed in the browser. |
Iv. apply usage
The usage of apply and call is different from that of call.
A. call (B, arg1, arg2 ...)
Apply (B, [arg1, arg2]) // apply has only two parameters, which call the parameters (arg1, arg2 ...) Put it in an array as the second parameter of apply