Two usage examples of call in Javascript

  • 2020-03-30 00:52:14
  • OfStack

Usage 1 (common usage) :

The representation is: an object. Method. Call (another object), meaning to replace the current object with another object, to execute the method of the current object. Here's an example:


function Class1(){
    this.name = "class1";
    this.showName = function(){
        alert(this.name);
    }
}
function Class2(){
    this.name = "class2";
}
var c1 = new Class1();
var c2 = new Class2(); 
c1.showName.call(c2);
c2.showName();        //Cannot perform

We first defined two separate functions, Class1 and Class2, the main difference being that there is one more showName() method than Class1. Then we define the corresponding objects c1 and c2, and we know clearly that c1 has a showName() method and c2 does not. But by some miracle, when we execute c1.shoname.call (c2), the name value of c2, "class2", pops up. In fact, we still execute the methods of c1, we just temporarily replace the object c2 with the object c1, after the execution, they are still as they were defined, c2 does not have any more methods. To check if there are more methods for c2, the example adds the line c2.shownmae (); It can't be executed, the browser will say Object #< Class2 > Has no method 'showName' error.

Why do this? As mentioned earlier, this is an AD hoc way of using it, and we are just taking advantage of its efficient programming. But this is not without limits, assuming that c1 and c2 represent the replaced objects and the replaced objects, and fun1 represents the methods inherent in c1. 1. When fun1 does not need parameters and does not need any local variables in the parent function, there is no difference between c1.fun1.call(c2) and c1.fun1(). 2. When fun1 does not need parameters but USES variables in the parent function, it is required to generate variables with the same name for functions of c1 and c2 that are used by fun1; 3. When the parameter of fun1 is needed, the form should be changed to c1.fun1.call(c2, parameter 1, parameter 2... At this time, the variable name in the function that generates c1 need not be the same as the variable name of the function that generates c2. In fact, when we use this usage of call, c2 and c1 are often similar in structure and function, so the above three points can be easily avoided.

Use 2:

Call (this), which can clone all the variables and methods of another existing function into its own function, realizes a function similar to inheritance. Here's an example:


function Animal(name){
    this.name = name;
    this.showName = function(){
        alert(this.name);
    }
};
var animal = new Animal("small_animal");
animal.showName();    //alert("small_animal")
function Cat(name){
    Animal.call(this, name);
};
//var Animal = null;    // Uncomment and try 
var cat = new Cat("black_cat");
cat.showName();     //alert("black_cat")


Related articles: