Uncaught TypeError:在JavaScript中非法调用 [英] Uncaught TypeError: Illegal invocation in javascript
问题描述
我创建了一个lambda函数,用一个具体的参数执行第二个函数。这个代码在Firefox中工作,但不在Chrome中,它的检查器显示一个奇怪的错误, Uncaught TypeError:非法调用
。我的代码有什么问题?
var make = function(callback,params){
callback(params);
}
make(console.log,'it will be accepted!');
控制台的日志功能需要这个
引用控制台(内部)。考虑这个复制你的问题的代码:
var x = {};
x.func = function(){
if(this!== x){
throw new TypeError('Illegal invocation');
}
console.log('Hi!');
};
//工作!
x.func();
var y = x.func;
//引发错误
y();
下面是一个可以工作的(愚蠢的)例子,因为它绑定了 this 到
console
在您的make函数中:
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!');
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!');
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!');
这篇关于Uncaught TypeError:在JavaScript中非法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!