The use of the call function and apply in Javascript:
The call function and the Apply function in JavaScript are switches to the execution context, which is performed by switching a function from the currently executing context to another object, for example:
SourceObj.method.call (DESTOBJ,PARAMS1,PARAMS2) is the method function in Sourceobj is placed in the Destobj execution
The call function has another important role to play in JavaScript object-oriented programming, such as:
function ParentClass () { this. Showtext (text) { alert (text); }}; function Inherentclass () { Parentclass.call (this);}; var instance=New inherentclass (); Instance.showtext (' inherent caller ');
View Code
Of course, it is possible to implement multiple inheritance in this way, just by invoking the call method with each parent class in the subclass.
The same applies and call functions, except that the parameters passed in are different, the first parameter in the argument list of the Apply function and the call function is the same, the second argument in the call function can be any argument, and the second argument of the Apply function must be an array. And the Apply function can only have 2 parameters.
Here's a quick demo of how to use the Apply function:
function Sourceobj (firstprams,secondparams) { alert (firsparams+secondparams);} function Destobj (firstparams,seconparams) { alert (firstparams*secondparams);} Sourceobj.apply (destobj,[6,2]); // result=12
View Code
The use of the call function and the Apply function in JavaScript