Home > Article > Web Front-end > Two usage examples of call in Javascript_javascript skills
Usage 1 (common usage):
The expression is: an object.method.call(another object), which means to replace the current object with another object and execute the method of the current object. Let’s look at the example first:
c1.showName.call(c2);
c2.showName(); //Cannot be executed
We first defined two functions, namely Class1 and Class2. The main difference between them is that Class2 has one more showName() method than Class1. Then the objects c1 and c2 corresponding to Class1 and Class2 are defined. At this time, we clearly know that c1 has the showName() method but c2 does not. But a miracle happened. When we execute c1.shoName.call(c2), the name value of c2, namely "class2", will pop up. In fact, we are still executing the methods of c1, but we just temporarily replaced the object c2 with the object c1. After the execution, they are still the same as when they were defined, and c2 does not have any more methods. In order to detect whether c2 has more methods, the example adds the line c2.showNmae(); It cannot be executed, and the browser will report the error Object #
Why do you do this? As mentioned before, this is a temporary usage method, we just use it for efficient programming. But this is not without limitations. Suppose that c1 and c2 are used to represent the replaced object and the replacement object, and fun1 is used to represent the inherent method of c1. 1. When fun1 does not require parameters and does not use any local variables in the parent function, there is actually no difference between c1.fun1.call(c2) and c1.fun1(); 2. When fun1 does not require parameters but uses the parent function variables in, then it is required to generate the variables used by fun1 with the same names in the functions of c1 and c2; 3. When fun1 requires parameters, the form must be rewritten as c1.fun1.call(c2, parameter 1, parameter 2 , ...parameter n), at this time, the variable name in the function that generates c1 does not have to have the same name as the variable name in the function that generates c2, it only needs to correspond. In fact, when we use call, c2 and c1 often have great similarities in structure and function, so the above three points are easy to avoid.
Usage 2:
Used in the definition process of function, in the form of: another existing function.call(this), which can clone all the variables and methods of another existing function into its own function, achieving a similar Inherited functionality. Take an example:
var animal = new Animal("small_animal");
animal.showName(); //alert("small_animal")
function Cat(name){
Animal.call(this, name);
};
//var Animal = null; //Uncomment and give it a try
var cat = new Cat("black_cat");
cat.showName(); //alert("black_cat")