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

javascript - Passing console.log as listener for events - Stack Overflow

programmeradmin1浏览0评论

See the following fiddle: /

I would like to use console.log as a listener for an event :

badButton.addEventListener('click', console.log);

As demonstrated in the fiddle, this will result in an error.

I understand how to circumvent the error (by wrapping console.log in another function). What I would like to know is why the error happens. Is there some security feature preventing the use of native functions being used in this way?

See the following fiddle: http://jsfiddle/calvintennant/jBh3A/

I would like to use console.log as a listener for an event :

badButton.addEventListener('click', console.log);

As demonstrated in the fiddle, this will result in an error.

I understand how to circumvent the error (by wrapping console.log in another function). What I would like to know is why the error happens. Is there some security feature preventing the use of native functions being used in this way?

Share Improve this question edited May 15, 2013 at 15:34 Alberto Zaccagni 31.6k11 gold badges75 silver badges107 bronze badges asked May 15, 2013 at 15:29 user1357678user1357678 2
  • 1 Please include the relevant code within your question. – James Montagne Commented May 15, 2013 at 15:30
  • 1 which browser(s) are you testing with? I guess Chrome because I get an error in Chrome. But it works in IE9, and fails silently in Firefox. – Spudley Commented May 15, 2013 at 15:35
Add a ment  | 

1 Answer 1

Reset to default 6

That's because inside the log function, this must be the console (it's implementation dependant). If you pass it directly as event handler, this would be the widget as you can see by trying

goodButton.addEventListener('click', function(e) { console.log(this);});

Another solution than wrapping it in a function you create is to pass console.log.bind(console) (but not if you want to be patible with IE8) :

goodButton.addEventListener('click', console.log.bind(console));
发布评论

评论列表(0)

  1. 暂无评论