Reputation: 4516
I am passing function to other function. It returns Uncaught TypeError: Illegal invocation
when passing native console.log
function to it. Why's that?
var functionToUse = console.log,
parameterToUse = 'Hello World!';
function execute(logic, parameter) {
if (parameter) {
logic(parameter);
} else if (!parameter) {
logic();
}
}
execute(function () { alert(1) }, false); // works fine
execute(functionToUse, parameterToUse); // Uncaught TypeError: Illegal invocation
Upvotes: 0
Views: 87
Reputation: 43718
You need to bind the log
function to the console
object when you pass it around.
Otherwise the this
value internally will point to window
and it will result in an illegal invocation.
var functionToUse = console.log.bind(console);
This would result in an illegal invocation as well:
console.log.call(window);
Upvotes: 1