A brief analysis of apply of method in Javascript

  • 2020-05-16 06:20:06
  • OfStack

We talked about the Javascript Call method before, but this time we'll talk about the apply method, which is similar to the Call method.

apply vs call

The difference between the two is whether a parameter is passed or an array of parameters

This is the use of call


theFunction.call(valueForThis, arg1, arg2, ...)

And this is apply

theFunction.apply(valueForThis, arrayOfArgs)

so

arrayOfArgs = [arg1, arg2, ...];

Javascript apply method

Let's look at the previous usage of call


function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}
print.call(undefined, "Hello", "World");

From the above statement, we can get that when

    args =  "Hello", "World";
function print(p1, p2) {
    console.log( p1 + ' ' + p2);
}
print.call(undefined, args);

They are equivalent, and in fact they are equivalent, and the output is also "Hello,World"!


Related articles: