console.log在函数中传递时出现非法调用错误 [英] Illegal Invocation error when console.log passed in a function

查看:133
本文介绍了console.log在函数中传递时出现非法调用错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此感到困惑。
请找到如下代码。

  var o = {
printToConsole:function(f){
F(1);
}
};

o.printToConsole(console.log);

// TypeError:非法调用 //我得到一个TypeError



从console.log的定义中我们得到这个

  

$ p $在cron中,它清晰地显示它没有任何参数,但是当我们尝试在控制台上打印东西时,我们会这样写,即将参数传递给console.log。

  console.log('带我进入控制台'); 

为什么我得到这个TypeError以及这个console.log如何在chrome中运行?

解决方案

更改

  o.printToConsole .LOG); 

  o.printToConsole(console.log.bind(控制台)); 

  o.printToConsole(function(){console.log.apply(console.log,arguments)}); 

console.log 函数仅适用于接收者( this )就是控制台(事实上,它依赖于浏览器)。


I am bit confused over this. Please find the code as below.

var o={
 printToConsole: function(f){
   f(1);
}
};

o.printToConsole(console.log);

//TypeError: Illegal invocation// I get a TypeError

From the definition of console.log we get this

`function log() { [native code] }`

In chrome, which clearly displays that it doesn't take any argument, though when we try to print things on console we do write like this i.e. pass the argument to console.log.

console.log('Take me on Console');

Why I am getting this TypeError and how this console.log behaves in chrome?

解决方案

Change

o.printToConsole(console.log);

to

o.printToConsole(console.log.bind(console));

or

o.printToConsole(function(){ console.log.apply(console.log, arguments) });

The console.log function only works when the receiver (this) is the console (in fact, it's browser dependent).

这篇关于console.log在函数中传递时出现非法调用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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