0

I'm trying to wrap console.log to make it shorter:

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

Why does this usage fail?

// this fails
var a=[1,2,3,4];
log(a);

Errors:

  • Chrome: "Illegal Invocation"
  • IE: fails silently
  • FF: TypeError: 'log' called on an object that does not implement interface Console."
JustAsking
  • 157
  • 1
  • 10
  • Yes, it depends where you run it, it works fine in Node. `console` is not JavaScript, it is provided by the environment. – elclanrs Dec 30 '14 at 06:53

2 Answers2

2

I've always seen it as:

function log(){console.log.apply(console,arguments);}
Ehtesh Choudhury
  • 7,452
  • 5
  • 42
  • 48
  • Yes, it makes sense to include the console as context. I'll give this a try. Thanks! BTW, is `log` a reserved word--see madforstrength's comment in my question? – JustAsking Dec 30 '14 at 06:54
  • Just tried your solution--works fine now! Thank you :) – JustAsking Dec 30 '14 at 06:57
  • Why are you giving it `null` as a context? `console.log` expects `this` to be `console`, so give it `console`. – user229044 Dec 30 '14 at 06:57
  • @meagar: Yes, that was my error. It now works fine when I feed it `console` instead of `null`. – JustAsking Dec 30 '14 at 07:02
  • 1
    @JustAsking `log` is not reserved, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords – Leo Dec 30 '14 at 07:02
-1

@Ehtesh corrected your syntax, alternatively you can use these methods, as console.log.apply not works in old versions of IEs (console.log.apply not working in IE9).

Method1:

function log(p_sMessage) {
    if(!Debug) { return; }
    else { if(window.console) { console.log(p_sMessage); }}
}

Method 2:

var log = Debug && window.console ? window.console.log.bind(window.console) : function() {};

or

var log = (Debug && Window.prototype.Console) ? Window.prototype.console.log.bind(Window.prototype.Console) : function () { };

(Debug flag sets visibility of console messages exclusively)

N.B.: Method 1 works in all browsers (except those do not support console) but does not show the line number from where it was called. Method 2 shows the line number but not works in older IEs.

Kunj
  • 1,980
  • 2
  • 22
  • 34