Why can't console.log be called with .call ()

The code below returns a welcome popup.

alert.call(this, 'hello'); 

But the code below returns the error "TypeError: Illegal invocation".

 console.log.call(this, 'hello'); 

What is the difference between alert and console.log tools?

+5
source share
1 answer

alert - global method ( window.alert ). If you call it alert.call(this) , this is a window object.

Since the log is a method in the console object, it expects this be the console object itself, but you still call it with this ( window ), so you get an error message.

Running console.log.call(console, 'test') will work fine.

+10
source

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


All Articles