Aplicar () pregunta para javascript

I study the following code to log

console.log.apply( console, arguments );

Cual es el proposito de apply() están aquí?

¿Por qué no solo console.log("message", arguments)?


preguntado el 09 de enero de 11 a las 09:01

3 Respuestas

La apply() function calls another function with a given this valor y arguments provided as an array.

The reason for an implicit func.apply(obj, args) is to make sure that within func(), this se refiere a obj.

Respondido el 09 de enero de 11 a las 12:01

console.log("message", arguments)

llamadas log with two arguments, "message" and the array-like object arguments.

console.log.apply( console, arguments );

lo llama con 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. P.ej:

function foo(a, b, c)
  console.log.apply( console, arguments );

is roughly equivalent to:


Respondido el 09 de enero de 11 a las 12:01

For compatibility with IE9 console.log.apply(console, arguments); may be changed to Function.prototype.apply.call(console.log, console, arguments); - Víctor

I think both answer 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 feel 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 was a better approach than write 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 );

Respondido el 12 de Septiembre de 14 a las 17:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.