我正在创建一个lambda函数,用具体的参数执行第二个函数。这段代码在Firefox中可以工作,但在Chrome中无法工作,它的检查器显示了一个奇怪的错误:Uncaught TypeError: Illegal invocation
。我的代码有什么问题?
var make = function(callback,params){
callback(params);
}
make(console.log,'it will be accepted!');
我正在创建一个lambda函数,用具体的参数执行第二个函数。这段代码在Firefox中可以工作,但在Chrome中无法工作,它的检查器显示了一个奇怪的错误:Uncaught TypeError: Illegal invocation
。我的代码有什么问题?
var make = function(callback,params){
callback(params);
}
make(console.log,'it will be accepted!');
控制台的日志函数期望 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();
以下是一个(有些愚蠢的)示例,但它可以工作,因为它在你的make函数中将this
绑定到console
:
var make = function(callback,params){
callback.call(console, params);
}
make(console.log,'it will be accepted!');
这也能行。var make = function(callback,params){
callback(params);
}
make(console.log.bind(console),'it will be accepted!');
function make(callback, params) {
callback(params);
}
make(function(str){ console.log(str); }, 'it will be accepted!');
console.log.bind(console)
替换console.log
,它可以在Chrome 12中工作。 - Dan D.make
函数等同于callback.call(null,params)
。 - Jan Turoň