plhn
plhn

Reputation: 5263

why use an 'apply' function in this situation?

in Chrome's console,

> $$
bound: function ()
{
    return document.querySelectorAll.apply(document, arguments)
}

why is this code like this? what's difference with

   return document.querySelectorAll(arguments)

?

Upvotes: 1

Views: 170

Answers (2)

Alnitak
Alnitak

Reputation: 339796

Using .apply() ensures that the arguments supplied to bound() are unwrapped before being supplied to querySelectorAll().

Without this, the effect of invoking:

bound('foo');

would be to call

document.querySelectorAll(['foo']);

Upvotes: 2

SLaks
SLaks

Reputation: 887365

arguments is an array-like object.

Calling document.querySelectorAll(arguments) will pass the entire array as a single parameter.
Calling querySelectorAll.apply(document, arguments) will pass each item in the array as a separate parameter.

In this particular case, it's not very useful, since querySelectorAll can only take one argument.

Upvotes: 2

Related Questions