Home >Web Front-end >JS Tutorial >Example analysis of call() and apply() methods in javascript_Basic knowledge
1. Method definition
call method:
Syntax: call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Definition: Call a method of an object to replace the current object with another object.
Description:
The call method can be used to call a method on behalf of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.
If the thisObj parameter is not provided, the Global object is used as thisObj.
apply method:
Syntax: apply([thisObj[,argArray]])
Definition: Apply a method of an object to replace the current object with another object.
Description:
If argArray is not a valid array or is not an arguments object, a TypeError will be caused.
If neither argArray nor thisObj are provided, the Global object will be used as thisObj and no parameters can be passed.
2. Common examples
a、
add.call(sub,3,1);
What this example means is to replace sub with add, add.call(sub,3,1) == add(3,1), so the running result is: alert(4); // Note: in js The function is actually an object, and the function name is a reference to the Function object.
b、
call means to put animal's method on cat for execution. Originally, cat did not have a showName() method. Now, animal's showName() method is put on cat for execution, so this.name should be Cat
c. Implement inheritance
Animal.call(this) means using the Animal object instead of this object. Then doesn’t Cat have all the properties and methods of Animal? The Cat object can directly call the methods and properties of Animal.
d. Multiple inheritance
It’s very simple, use two calls to achieve multiple inheritance
Of course, there are other ways to inherit js, such as using the prototype chain. This is not within the scope of this article. I just explain the usage of call here. Speaking of call, and of course apply, these two methods basically mean the same thing. The difference is that the second parameter of call can be of any type, while the second parameter of apply must be an array, or it can be arguments
And callee, caller..
Summary:
To put it simply: the same point: the effects of the two methods are exactly the same
Difference: The parameters passed by the method are different