2

going back to writing javascript for the time being, i wonder why this isn't possible

[array].forEach(console.log)
user2167582
  • 5,986
  • 13
  • 64
  • 121
  • what is the value of `array` – chiliNUT Mar 10 '15 at 21:18
  • you can write your own prototype. http://code.tutsplus.com/tutorials/prototypes-in-javascript--net-24949 – Pedro Estrada Mar 10 '15 at 21:19
  • 1
    You can do that (just did it in Firebug), as long as `array` is defined. Are you just not getting back what you expected? What were you expecting? – talemyn Mar 10 '15 at 21:21
  • 2
    Possible duplicate of [Why doesn't console.log work when passed as a parameter to forEach?](http://stackoverflow.com/questions/9639167/why-doesnt-console-log-work-when-passed-as-a-parameter-to-foreach) – Knu May 23 '16 at 00:57

3 Answers3

6

Because console.log.bind(console), otherwise the .log() method of a console object is invoked with a wrong context.

The general rule to follow is: the method must be called with a proper context unless it's stated otherwise.

So in this particular case no one states it can be invoked with say undefined, so you should not expect it to work. And even if it does - you should not rely on it.

zerkms
  • 249,484
  • 69
  • 436
  • 539
6

It will work correctly in certain browsers and not in others.

A major point of confusion in Javascript is the way this behaves. Often these will produce vastly different behavior:

myObj.method();

var a = myObj.method;
a();

What you are doing there is passing console.log as a function into forEach, which is separating it from the object it is attached to. This will cause any uses of this inside the log method to refer to the wrong thing, and quite possibly cause the method to not work correctly.

To remedy this, you can pass a thisArg into .forEach:

[array].forEach(console.log, console);

or use .bind():

[array].forEach(console.log.bind(console));
JLRishe
  • 99,490
  • 19
  • 131
  • 169
2

You can, if the browser supports it, although even then you shouldn't rely on it.

The reason it doesn't work on some browsers is that passing a function reference like this (even if that function is a property of an object such as console) doesn't set the this context correctly within that function.

When the (browser specific) implementation of the log function tries to access its this variable it finds that instead of referring to console it actually refers to the global object.

To fix it, you can use this:

[array].forEach(console.log.bind(console));

where the .bind call returns a new function wrapping the original function and whose context is set to the passed parameter (e.g. console)

Alnitak
  • 334,560
  • 70
  • 407
  • 495