1. Method definitions.
Call method:
Syntax: Call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Definition:invokes one method of an object, replacing the current object with another object.
Description
The call method can be used to invoke a method in place of another object. The call method can change the object context of a function from the initial context to a new object specified by Thisobj.
If the Thisobj parameter is not provided, then the Global object is used as the thisobj.
Apply method:
Syntax: Apply ([Thisobj[,argarray]])
Definition: a method of applying an object that replaces the current object with another object.
Description
If Argarray is not a valid array or is not a arguments object, it will result in a TypeError.
If none of the Argarray and Thisobj parameters are provided, then the Global object is used as a thisobj and cannot be passed any parameters.
2. Example
function Add (A, b) {Console.log (A + b);} function sub () {Console.log (A-B);} Add.call (Sub, 3, 1);//result:4
Parsing: JS inside the method are objects. Point the this pointer inside the add to the sub. So the result is a + B.
function person () {this.name = ' person '; This.show = function () {console.log (this.name); }}function worker () {this.name = ' worker ';} var p = new Person (), var w = new Worker ();p. Show.call (w); Result:person
Parse: Executes the Show method inside the P object and points the this pointer inside the P object to W.
function person (name) {this.name = name; This.show = function () {console.log (this.name); }}function Worker (name) {Person.call (this, name);} var w = new Worker (' Zhangsan '); W.show ();
The understanding of call and apply in JS