未捕获的类型错误:javascript 中的非法调用 [英] Uncaught TypeError: Illegal invocation in javascript
本文介绍了未捕获的类型错误:javascript 中的非法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个使用具体参数执行第二个函数的 lambda 函数.此代码在 Firefox 中有效但在 Chrome 中无效,其检查器显示一个奇怪的错误,Uncaught TypeError: Illegal invocation
.我的代码有什么问题?
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!');
推荐答案
控制台的日志函数期望 this
引用控制台(内部).考虑复制您的问题的这段代码:
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();
这是一个可以工作的(愚蠢的)例子,因为它在你的 make 函数中将 this
绑定到 console
:
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!');
这也行
var make = function(callback,params){
callback(params);
}
make(console.log.bind(console),'it will be accepted!');
这篇关于未捕获的类型错误:javascript 中的非法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文