Apply () question for javascript

I am studying the following code for the magazine

console.log.apply( console, arguments ); 

What is the purpose of apply() here?

Why not just console.log("message", arguments) ?

Thank.

+6
javascript
Jan 09 2018-11-11T00:
source share
3 answers

The apply() function calls another function with the given value this and arguments as an array.

The reason for implicit func.apply(obj, args) is to make sure inside func() , this refers to obj .

+7
Jan 09 2018-11-11T00:
source share
 console.log("message", arguments) 

calls log with two arguments, a "message" and array type arguments.

 console.log.apply( console, arguments ); 

calls it with arguments n , where n is the length of the arguments of an array type object. In other words, the arguments are expanded into separate arguments. Method Context: console . For example:.

 function foo(a, b, c) { console.log.apply( console, arguments ); } foo(1,2,3); 

approximately equivalent:

 console.log(1,2,3); 
+8
Jan 09 2018-11-11T00:
source share

I think both answers did not explain WHY. The real brilliant use of this method for programming.

I did not like the first voted answer, I could not understand it even after reading it three times, and the second felt incomplete.

I think the main purpose of writing this way is to use it inside a function (or closure).

So, this line only makes sense inside your custom registrar: console.log.apply (console, arguments);

There was probably a better approach than writing 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 ); } 
+1
Sep 12 '14 at 13:23
source share



All Articles