console.log在分配给新变量时崩溃了吗?

时间:2014-02-27 22:09:57

标签: javascript google-chrome console.log

所以这适用于firefox和opera,但不适用于chrome或IE。

        window.onload=function(){

            IMS=new Object();
            IMS.putLog=console.log;


            IMS.putLog('IMS Initialized...');

            IMS.putLog('Loading...');
            loadData(userName, passWord);
            IMS.putLog('Loaded...');
        };

非法调用失败

不知道为什么?有什么建议吗?

2 个答案:

答案 0 :(得分:2)

原因是当您调用IMS.putLog时,该函数的this变量为IMS; console.log实施可能指望thisconsole

这是一种解决方法:

IMS.putLog = console.log.bind(console);

这将确保在调用日志函数时thisconsole

不幸的是,这不适用于IE< 9,或者其他浏览器。我知道bind在PhantomJS中不起作用,如果重要的话。

答案 1 :(得分:1)

请参阅:"Uncaught TypeError: Illegal invocation" in Chrome

基本上,当您重新分配console.log时,它会更改范围。我猜它在Firefox和Opera中运行正好。

更好的解决方案是:

IMS.putLog = function(){
   console.log.apply(console, arguments); //any passed to IMS.putLog will get passed to console.log
};

同样的结果,只是在正确的范围内调用。

编辑:这应该适用于所有支持console.log的浏览器 Edit2:Brainfart - 需要应用参数