0

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
Szymon Toda
  • 4,454
  • 11
  • 43
  • 62

1 Answers1

1

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);
plalx
  • 42,889
  • 6
  • 74
  • 90