Here are the main solutions to apply and call the following questions:
(1) common usage of call and apply
(2) The difference between call and apply
1. First we look at the basic definitions of call and apply usage:
Apply: Methods can hijack another object's method, inheriting another object's properties.
Fn.apply (Obj,args)
OBJ: The object of the Hijack function fn method, which is common in the way that obj is substituted with this and referenced by the actual object;
Args: Can be seen as an array, which passes parameters to FN;
Fn.call (obj,[param1[,param2[,... [Paramn]])
The difference between apply and call is limited to parameters, and the call() method accepts a list of several parameters , and the apply() method accepts an array with multiple parameters . Here we give an example to compare
function partial (FN, str1, str2) { function result (STR3) { return fn.call (this , str1, str2, STR3); } return result;}
function partial (FN, str1, str2) { function result (STR3) { return fn.apply (this< /c5>, [str1, STR2, STR3]); } return result;
It is also important to note that when no object is called on the Apply function, this can be replaced with NULL, which points to the global variable window;
2. Let's look at a simple apply application
<script> function argsasarray (FN, arr) { return fn.apply ( this , arr) } Console.log ( argsasarray (function (greeting, name, punctuation) { return greeting + ', ' + name + (Punctuation | | ‘!‘ ); }, [' Hello ', ' Ellie ', '! ' ]) )</script>
Analysis: Fn.apply (This,arr) in Console.log, we create an entity object, at which point this represents Argsasarray (...). {...}。 The return result is hello,ellie!
One thing to note here is that we know that when we call the Argsasarry object, we need not an array, but a parameter, because apply can convert an array by default to a list of arguments. such as ([PARAM1,PARAM2,PARAM3] converted to PARAM1,PARAM2,PARAM3.
There are more flexible uses for apply and call, but the more complex effects are not difficult to implement based on the understanding of basic grammar. Welcome to have more programming-loving partners in the comment area to discuss with me
The call () and apply () methods in JS