Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply() question for javascript

Tags:

javascript

I study the following code to log:

console.log.apply( console, arguments );

What is the purpose of apply() here?

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

like image 910
Ricky Avatar asked Jan 09 '11 09:01

Ricky


People also ask

How do I ask a question in JavaScript?

Prompt Box in JavaScript To ask for user input in JavaScript, you can use the built-in prompt box. To show a prompt, use the prompt() method.

What is JavaScript best answer?

JavaScript is a popular web scripting language and is used for client-side and server-side development. The JavaScript code can be inserted into HTML pages that can be understood and executed by web browsers while also supporting object-oriented programming abilities.

What is JavaScript answer?

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages. The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.


2 Answers

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);
like image 199
Matthew Flaschen Avatar answered Oct 12 '22 02:10

Matthew Flaschen


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.

like image 38
Linus Kleen Avatar answered Oct 12 '22 03:10

Linus Kleen