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?
- 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
1 Answer
Reset to default 6That'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));