最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why can't console.log be called using .call() - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 11

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.

发布评论

评论列表(0)

  1. 暂无评论