3

Rather a technical question concerning JavaScript events:

Why does

window.onmousewheel = console.log;

throw an Uncaught TypeError: Illegal invocation, while

window.onmousewheel = function (e) {console.log(e); };

works just as expected and prints the event as string? Why is the console.log, when assigned to window.onmousewheel, not just called with one parameter like the lambda expression?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Simon
  • 59
  • 5
  • [Chrome doesn't recognize console.log...](http://stackoverflow.com/questions/9612398/chrome-doesnt-recognize-console-log-when-its-called-log) ... http://stackoverflow.com/questions/8904782/uncaught-typeerror-illegal-invocation-in-javascript ... http://stackoverflow.com/questions/16615781/why-is-console-log-illegaly-invocated-as-a-function-parameter ... http://stackoverflow.com/questions/12944987/abbreviating-console-log-in-javascript ... http://stackoverflow.com/questions/5133649/alias-to-chrome-console-log ... http://stackoverflow.com/questions/5456709/create-shortcut-to-console-log-in-chrome –  Jul 29 '13 at 17:38
  • http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9 – Igor Dymov Jul 29 '13 at 17:39
  • 5
    Try `window.onmousewheel = console.log.bind(console);`. – Ted Hopp Jul 29 '13 at 17:40
  • 1
    This is more of a question about why `foo.bar()` is different to `fn = foo.bar; fn()`. – Paul S. Jul 29 '13 at 17:41

2 Answers2

7

When function is called without explicit receiver, the receiver is window (or more generally the global object) or undefined depending on strictness. The function referenced by console.log requires that its this value is an instance of Console.

It is not usually done in user code but you could protect your methods from generic calls as well:

MyClass.prototype.method = function() {
    if( !( this instanceof MyClass ) ) {
        throw new Error("Invalid invocation");
    }
};
Esailija
  • 138,174
  • 23
  • 272
  • 326
3

It all has to do with the scope of console.log

You should do:

window.onmousewheel = console.log.bind(console);

Naftali
  • 144,921
  • 39
  • 244
  • 303