未捕获的类型错误:javascript 中的非法调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8904782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Illegal invocation in javascript
提问by fcortes
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?
我正在创建一个 lambda 函数,该函数使用具体参数执行第二个函数。此代码在 Firefox 中有效,但在 Chrome 中无效,其检查器显示一个奇怪的错误,Uncaught TypeError: Illegal invocation
。我的代码有什么问题?
var make = function(callback,params){
callback(params);
}
make(console.log,'it will be accepted!');
回答by Paul
The console's log function expects this
to refer to the console (internally). Consider this code which replicates your problem:
控制台的日志功能期望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();
Here is a (silly) example that will work, since it binds this
to console
in your make function:
这是一个可以工作的(愚蠢的)示例,因为它绑定this
到console
您的 make 函数中:
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!');
回答by ifreedom
You can wrap the function which need 'this' to a new lambda function, and then use it for your callback function.
您可以将需要“this”的函数包装到新的 lambda 函数中,然后将其用于回调函数。
function make(callback, params) {
callback(params);
}
make(function(str){ console.log(str); }, 'it will be accepted!');