Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

The below code returns a pop-up window with 'hello'.

alert.call(this, 'hello');

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

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

What is the difference in the implements of alert and console.log?

like image 978
Nigiri Avatar asked Aug 18 '14 07:08

Nigiri


1 Answers

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

Because log is a method in the console object, it expects this to be the console object itself, but you are still calling it with this(window), so you get an error.

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

like image 58
John Sterling Avatar answered Oct 07 '22 23:10

John Sterling