Why does console.log.apply() throw an Illegal Invocation error? [duplicate]
Solution 1:
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
.
Solution 2:
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')