Home  >  Article  >  Web Front-end  >  A brief analysis of the apply() method in Javascript_javascript skills

A brief analysis of the apply() method in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:09:201393browse

We talked about the Javascript Call method before. This time we will talk about the apply method, which is similar to the Call method.

apply vs call

The difference between the two is: is it a parameter or an array of parameters that is passed

This is how to use call

Copy code The code is as follows:

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

And this one is apply
Copy code The code is as follows:

theFunction.apply(valueForThis, arrayOfArgs)

Therefore
Copy code The code is as follows:

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

Javascript apply method

Let’s take a look at the previous usage of call

Copy code The code is as follows:

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

From the above description, we can conclude that when
Copy code The code is as follows:

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

The two are equivalent, and in fact they are also equivalent, and the output result is also "Hello, World"!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn