Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does console.log.apply() throw an Illegal Invocation error? [duplicate]

When I execute the following code in Chrome 18 beta I get the error:

console.log.apply(this, ['message']); 

TypeError: Illegal invocation.

In Firefox 10 it works as expected.

In IE9 I get the error: Object doesn't support property or method 'apply'.

I'm guessing this has to do with how the browser has implemented console.log.

Why does it work in Firefox but not in Chrome and IE? I'm hoping someone can shed some light on the cause of this and its ramifications.

Here is an executable sample on JS Bin.

like image 462
joshuapoehls Avatar asked Mar 01 '12 18:03

joshuapoehls


2 Answers

console and log are host objects. Their behavior is implementation dependent, and to a large degree are not required to implement the semantics of ECMAScript.

FWIW, your jsBin fails in Chrome as well unless you change it to...

console.log.apply(console, ['message']); 

but that seems to be that log simply anticipates a calling context of console.

like image 170
user1106925 Avatar answered Sep 28 '22 00:09

user1106925


Here's an alternate solution. I'm not sure the case where there are no args works as expected.

function logr(){     var i = -1, l = arguments.length, args = [], fn = 'console.log(args)';     while(++i<l){         args.push('args['+i+']');     };     fn = new Function('args',fn.replace(/args/,args.join(',')));     fn(arguments); }; logr(1,2,3); logr(); logr({},this,'done') 
like image 35
jimmont Avatar answered Sep 28 '22 01:09

jimmont