This snippet is cut from Secrets of the JavaScript Ninja.
function log() { try { console.log.apply( console, arguments ); } catch(e) { try { opera.postError.apply( opera, arguments ); } catch(e){ alert( Array.prototype.join.call( arguments, " " ) ); } } }
Why should I use apply and what's the difference between console.log.apply(console, arguments)
and console.log(arguments)
?
This is the expression to use if your intention is to obtain something. You apply for scholarship money. You apply for admission. You apply for a job.
The apply method is used for allowing a function/object belonging to an object x to be called and assigned to an object y.
Apply functions are a family of functions in base R which allow you to repetitively perform an action on multiple chunks of data. An apply function is essentially a loop, but run faster than loops and often require less code.
In JavaScript, you can use call() , apply() , and bind() methods to couple a function with an object. This way you can call the function on the object as if it belonged to it. The call() and apply() are very similar methods. They both execute the bound function on the object immediately.
In this case, the log function may accept any number of arguments.
Using .apply()
, it doesn't matter how many arguments are passed. You can give the set to console.log()
, and they will arrive as individual arguments.
So if you do:
console.log(arguments)
...you're actually giving console.log
a single Arguments
object.
But when you do:
console.log.apply( console, arguments );
...it's as though you passed them separately.
Other useful examples of using .apply()
like this can be demonstrated in other methods that can accept a variable number of arguments. One such example is Math.max()
.
A typical call goes like this:
var max = Math.max( 12,45,78 ); // returns 78
...where it returns the largest number.
What if you actually have an Array of values from which you need the largest? You can use .apply()
to pass the collection. Math.max
will think they were sent as separate arguments instead of an Array.
var max = Math.max.apply( null, [12,45,92,78,4] ); // returns 92
As you can see, we don't need to know in advance how many arguments will be passed. The Array could have 5 or 50 items. It'll work either way.
If you have
function log() { console.log.apply(console, arguments); }
and call it like log('foo');
then that translates to console.log.apply(console, ['foo']);
which is equivalent to console.log('foo');
which is what you want.
If you defined it like
function log() { console.log(arguments); }
instead then log('foo');
would be equivalent to log(['foo']);
which is not what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With