Reputation: 1576
In the excellent book JavaScript Patterns by Stoyan Stefanov he gives the following example as a one-off callback:
document.addEventListener("click", console.log, false);
In Chrome this throws an Uncaught TypeError: Illegal invocation
In Firefox it throws TypeError: 'log' called on an object that does not implement interface Console.
In Safari it throws a generic TypeError: Type error
. I'm not sure why. Any thoughts?
Upvotes: 1
Views: 666
Reputation: 896
console is actually an object and the method log() needs the scope to access this object, e.g.
document.addEventListener("click", console.log.bind(console, "test"), false);
Upvotes: 3
Reputation: 1576
I realized that O'Reilly books usually have an "errata" page on line, and sure enough there was my answer (page 66).
document.addEventListener("click", console.log.bind(console), false);
http://www.oreilly.com/catalog/errataunconfirmed.csp?isbn=9780596806767
Upvotes: 0
Reputation: 3535
It's because console.log
is a native method and you can't invoke it in a different context. When you pass it around as a callback, you basically assign it to a different context. Same happens if you do the following:
var foo = console.log;
foo(1, 2, 3);
Here's a reference SO answer.
Upvotes: 0
Reputation: 324600
It always helps to think what this
is.
The way you are calling console.log
, this
is unset (and unless you're in Strict Mode defaults to window
). However, the function expects this
to be console
, thus giving the "illegal invocation" and "called on an object that does not implement interface Console" - you are literally calling it on nothing (or the Window)
It seems like the code is intended to console.log
the event data, in which case you should explicitly do so:
document.addEventListener("click", function(e) {console.log(e);}, false);
Note that since it is being called "normally", this
will be console
as expected by the browser, and function as intended.
I would however recommend changing it to console.dir(e)
so that you can actually explore the object data, because I imagine [object PointerEvent]
isn't very useful.
Upvotes: 1
Reputation: 1874
console.log() is a function! So you can use like this;
document.addEventListener("click", function(){
console.log("test log");
}, false);
Upvotes: -1