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

See the following fiddle: I would like to use console.log as a listener for an event :badButton.addEve

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));

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742331066a4423730.html

相关推荐

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

    See the following fiddle: I would like to use console.log as a listener for an event :badButton.addEve

    13小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信