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?

4

2 Answers 2

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"); } }; 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the explanation, not some workaround!
3

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

You should do:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.