javascript - console.log 在分配给新变量时崩溃?

标签 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...');
        };

非法调用失败

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

最佳答案

原因是当你调用IMS.putLog时,函数的this变量是IMSconsole.log 实现可能指望 this 成为 console

解决方法如下:

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

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

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

关于javascript - console.log 在分配给新变量时崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22081618/

相关文章:

javascript - Angular 动态嵌套 ng-repeat 生成

javascript - window.open 不能正常工作

html - Chrome 打印预览错误

google-chrome - 检查网络响应是来自服务器还是 Chrome 缓存

javascript - Redux reducer 中尚未更新的控制台输出状态

JavaScript - 在显示 :none and display:block 之间添加转换

javascript - 如何使用 EJS 模板引擎将变量传递给内联 javascript?

javascript - 如何使用 Protractor 在 e2e 测试中预期元素的动态计数

javascript - console.log 和 JSON.parse 返回错误

JavaScript .无法理解为什么我的第一个控制台语句给出了未定义的