Javascript Uncaught TypeError:非法调用

时间:2012-12-06 06:18:50

标签: javascript

  

可能重复:
  Chrome doesn’t recognize console.log when it’s called log

当我将方法设置为console.log时,有人能告诉我为什么这不起作用吗?

var met = "console.log";
var msg = "HELLO WORLD";
var n = met.split(".");
var f = this;
$.each(n, function(k, v){
    f = f[v];
});
f(msg);

当我尝试使用alert

时,这似乎有效

2 个答案:

答案 0 :(得分:1)

这是因为控制台的日志功能被分配给f变量,但是在执行时它不再引用控制台范围。在处理回调或传递函数时,Javascript范围可能会变得棘手。

就@ Murali的评论而言,有些浏览器以不同于其他浏览器的方式实现console.log方法。

作为实验,请尝试运行此代码,看看它是否有效:

var met = "console.log";
var msg = "HELLO WORLD";
var n = met.split(".");
n[1].call(n[0], msg);

使用.call方法可以执行函数并声明其范围。如果这对您有用,那么重构循环场景应该很容易。

答案 1 :(得分:0)

解决了它。

var met = "console.log";
var msg = "HELLO WORLD";
var n = met.split(".");
var tail = n.pop();
var f = this;
$.each(n, function(k, v){
    f = f[v];
});
var func = function(){ f[tail].apply(f, arguments); }
func(msg);

在Chrome,Firefox,Opera和Safari上进行了测试。似乎不适用于IE9。

我从Link获得了@muistooshort的想法 以及Link

上的@jasonbunting