Uncaught TypeError: Illegal invocation in javascript

纵饮孤独 提交于 2019-11-26 01:54:22

问题


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 of my code?

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

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

回答1:


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!');



回答2:


You can wrap the function which need 'this' to a new lambda function, and then use it for your callback function.

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

make(function(str){ console.log(str); }, 'it will be accepted!');


来源:https://stackoverflow.com/questions/8904782/uncaught-typeerror-illegal-invocation-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!