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?

5
  • 1
    Try var cl = console.log.bind(console) instead. Commented Jun 22, 2015 at 14:24
  • 1
    Thanks, but what's wrong with my code? Commented Jun 22, 2015 at 14:25
  • 1
    Amply explained in the linked question. Commented Jun 22, 2015 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. Commented Jun 22, 2015 at 14:26
  • 1
    @ElgsQianChen: You're calling it with the wrong this. github.com/joyent/node/blob/master/lib/console.js#L48-L53 Commented Jun 22, 2015 at 14:27

1 Answer 1

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");

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but what's wrong with my code?
Thanks. Now I got the idea why. :)