What is the purpose of JavaScript's apply() in this case?
I study the following code to log:
con开发者_Go百科sole.log.apply( console, arguments );
What is the purpose of apply()
here?
Why not just console.log("message", arguments)
?
console.log("message", arguments)
calls log
with two arguments, "message" and the array-like object arguments.
console.log.apply( console, arguments );
calls it with n
arguments, where n
is the length of the array-like object arguments. In other words, arguments is unwrapped into individual arguments. The context of the method is console
. E.g.:
function foo(a, b, c)
{
console.log.apply( console, arguments );
}
foo(1,2,3);
is roughly equivalent to:
console.log(1,2,3);
The apply()
function calls another function with a given this
value and arguments
provided as an array.
The reason for an implicit func.apply(obj, args)
is to make sure that within func()
, this
refers to obj
.
I think both answers did not explain why. The real shiny use of this way to program.
I did not like the first voted answer. I could not understand it even reading thrice and the second one feels incomplete.
I think the main purpose to write this way is to use it inside a function (or closures).
So, this line only makes sense inside your customized logger: console.log.apply( console, arguments );
Probably it was a better approach than write to something like this:
function my_worse_way_to_log_dynamic_args ( [several dynamic arguments] )
{
// loop each argument
// call console.log for each one
}
function my_better_way_to_log_dynamic_args ( [several dynamic arguments] )
{
console.log.apply( console, arguments );
}
精彩评论