Uncaught TypeError:在JavaScript中非法调用 [英] Uncaught TypeError: Illegal invocation in javascript

查看:229
本文介绍了Uncaught TypeError:在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆