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?
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?
Share Improve this question edited Aug 18, 2014 at 7:52 idmean 14.9k9 gold badges61 silver badges89 bronze badges asked Aug 18, 2014 at 7:48 NigiriNigiri 3,6497 gold badges32 silver badges52 bronze badges 5- 2 @Teemu I think he wants to know why the 2nd yields that error :) – Silviu Burcea Commented Aug 18, 2014 at 7:52
- see more about Function.prototype.call and this keyword – Grundy Commented Aug 18, 2014 at 7:52
- @SilviuBurcea Then why not ask about it? – Teemu Commented Aug 18, 2014 at 7:53
- @Teemu I'm sorry about that.. – Nigiri Commented Aug 18, 2014 at 8:03
- console functions will be bound to console: codereview.chromium/1859293002 – adrianton3 Commented May 2, 2016 at 19:02
1 Answer
Reset to default 11alert
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.