未捕获的TypeError:javascript中的非法调用

fco*_*tes 36 javascript lambda functional-programming invocation

我正在创建一个lambda函数,它使用具体的params执行第二个函数.这个代码适用于Firefox,但不适用于Chrome,它的检查器显示一个奇怪的错误,Uncaught TypeError: Illegal invocation.我的代码出了什么问题?

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

make(console.log,'it will be accepted!');
Run Code Online (Sandbox Code Playgroud)

Pau*_*aul 63

控制台的日志功能期望this引用控制台(内部).请考虑以下代码复制您的问题:

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();
Run Code Online (Sandbox Code Playgroud)

这是一个(愚蠢的)例子,因为它在你的make函数中绑定thisconsole:

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

make(console.log,'it will be accepted!');
Run Code Online (Sandbox Code Playgroud)

这也行

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

make(console.log.bind(console),'it will be accepted!');
Run Code Online (Sandbox Code Playgroud)