4

I did this in my Angular app:

var cl = console.log;
cl(123);

however, I had the following error message:

Uncaught TypeError: Illegal invocation

This happened in Chrome. It works in Nodejs.

I'm confused. Is it illegal code?

  • 1
    Try `var cl = console.log.bind(console)` instead. – Andy Jun 22 '15 at 14:24
  • 1
    Thanks, but what's wrong with my code? –  Jun 22 '15 at 14:25
  • 1
    Amply explained in the linked question. – Amadan Jun 22 '15 at 14:26
  • 1
    There are many duplicates. Long story short, `console.log`'s implementation depends on the context method is run in. It means that `this` inside needs to be `console` object and nothing else. Hence, you should only run `console.log` method in context of the `console` object. What happens when you assign `var log = console.log` is that you detach function from the origin and it just looses context. – dfsq Jun 22 '15 at 14:26
  • 1
    @ElgsQianChen: You're calling it with the wrong `this`. https://github.com/joyent/node/blob/master/lib/console.js#L48-L53 – SLaks Jun 22 '15 at 14:27

1 Answers1

6

cl only references the log() method. log() expects console as context but gets window. To solve, bind console as context:

var cl = console.log.bind(console);
cl("Hello");