Illegal call error when console.log is passed to a function

I am a little confused by this. Please find the code as shown below.

var o={ printToConsole: function(f){ f(1); } }; o.printToConsole(console.log); 

//TypeError: Illegal invocation // I get a TypeError

From the definition of console.log we get this

 `function log() { [native code] }` 

In chrome, which clearly shows that it takes no arguments, although when we try to print information to the console, we write like this: pass the argument console.log.

 console.log('Take me on Console'); 

Why am I getting this TypeError and how does this console.log behave in chrome?

+6
source share
1 answer

Edit

 o.printToConsole(console.log); 

to

 o.printToConsole(console.log.bind(console)); 

or

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

The console.log function only works when the receiver ( this ) is the console (in fact, it depends on the browser).

+12
source

Source: https://habr.com/ru/post/952444/


All Articles