Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-3
rated 0 times [  2] [ 5]  / answers: 1 / hits: 41573  / 13 Years ago, wed, january 18, 2012, 12:00:00

I'm creating a lambda function that executes a second function with a concrete params. This code works in Firefox but not in Chrome, its inspector shows a weird error, Uncaught TypeError: Illegal invocation. What's wrong with my code?


var make = function(callback,params){
callback(params);
}

make(console.log,'it will be accepted!');

More From » lambda

 Answers
30

The console's log function expects this to refer to the console (internally). Consider this code which replicates your problem:



var x = {};
x.func = function(){
if(this !== x){
throw new TypeError('Illegal invocation');
}
console.log('Hi!');
};
// Works!
x.func();

var y = x.func;

// Throws error
y();


Here is a (silly) example that will work, since it binds this to console in your make function:



var make = function(callback,params){
callback.call(console, params);
}

make(console.log,'it will be accepted!');


This will also work



var make = function(callback,params){
callback(params);
}

make(console.log.bind(console),'it will be accepted!');

[#87954] Tuesday, January 17, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darleneh

Total Points: 231
Total Questions: 110
Total Answers: 94

Location: Spain
Member since Thu, Dec 23, 2021
3 Years ago
;