2013-07-29 3 views
3

скорее технический вопрос относительно событий JavaScript:События с родной против функций лямбда

Почему

window.onmousewheel = console.log; 

бросить Uncaught TypeError: Illegal invocation, в то время как

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

работает так же, как ожидается, и печатает событие как строка? Почему console.log, если присвоено window.onmousewheel, не просто вызвано одним параметром, как выражение лямбда?

Саймон

+0

[Chrome не распознает console.log ...] (HTTP: // StackOverflow .com/questions/9612398/chrome-doesnt-узнайте-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 –

+0

http://stackoverflow.com/questions/5538972/console-log-apply-not-working-in-ie9 –

+5

Попробуйте 'window.onmousewheel = console.log .bind (консоль); '. –

ответ

7

Когда функция вызывается без явного приемника, приемником является window (или, более общо, глобальное ob ject) или undefined в зависимости от строгости. Функция, на которую ссылается console.log, требует, чтобы ее значение this являлось экземпляром Console.

Это обычно не делается в коде пользователя, но вы могли бы защитить свои методы от общих вызовов, а также:

MyClass.prototype.method = function() { 
    if(!(this instanceof MyClass)) { 
     throw new Error("Invalid invocation"); 
    } 
}; 
+1

спасибо за объяснение, а не обходное решение! – Simon

3

Это все связано с областью console.log

You должны сделать:

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

Смежные вопросы