fox
fox

Reputation: 16486

javascript: what is the 'console' context in the example below?

Reading through this article about good interview questions for a JS coder linked off of HN today and got to the following part:

Next I'd ask a few simple questions designed to show me how well candidates understood the arguments object. I'd start off by calling the as-yet undefined log function.

log('hello world')

Then I'd ask the candidates to define log so that it proxies its string argument to console.log(). The correct answer is something along these lines, but better candidates will often skip directly to using apply.

function log(msg){   
    console.log(msg); 
}

Once that's defined I change the way I call log, passing in multiple arguments. I make clear that I expect log to take an arbitrary number of arguments, not just two. I also hint to the fact that console.log also takes multiple arguments.

log('hello', 'world');

The way that the writer explains his solution is via apply:

Hopefully your candidate will jump straight to using apply. Sometimes they'll get tripped up on the difference between apply and call, and you can nudge them to the correct direction. Passing the console context is also important.

function log(){
  console.log.apply(console, arguments);
};

I get here that the log function is leveraging apply and implicitly passing arguments in, so that a call like

log('hello', 'world');

will pass along console.log.apply(console, ['hello', 'world']), though my question is: what is the console context in this example, i.e. the first argument in the apply call above, and where does it come from?

Upvotes: 1

Views: 2133

Answers (1)

abyx
abyx

Reputation: 72748

console is just the object that has the log function defined on, and is, essentially, this in the log function, which is why it is being passed as the context. console is not some special word in the browser, it's just an object that was saved under window.console.

Upvotes: 3

Related Questions