Functions in JavaScript are objects, as well as other JS objects, where call and apply are among the more important methods that can be used to invoke functions indirectly. These two methods allow explicit invocation of this value, which means that all functions can be used as methods of any object, even if the function is not a method of that object.
Call Method:
Syntax:call ([thisobj[,arg1[, arg2[, [,. ArgN]]])
Apply method:
Syntax:apply ([Thisobj[,argarray]])
The call and apply methods work the same, but from the above syntax, they pass in different parameters, the first parameter of the two methods is the object that needs to invoke the method (thisobj), the function requires the argument called method is a list of incoming, The Apply method needs to pass in an array as an argument.
Instance:
1 functionpeople (name, age) {2 3 This. Name =name;4 This. Age =Age ;5 This. ShowName =function () {6 7Console.log ( This. Name);8 9 }Ten } One A - functionStudent (name, age) { - the This. Name =name; - This. Age =Age ; - This. Showage =function () { - +Console.log ( This. age); - } + } A at - varPeople =NewPeople ("Peoplename", 20); - varStudent =NewStudent ("Studentname", 10); - -People.showName.call (student);//Output Studentname
In the above code, you can also use People.showName.apply (student), output or studentname.