【问题标题】:console.log crashes when assigned to new variable?分配给新变量时,console.log 崩溃?
【发布时间】:2014-03-31 15:44:20
【问题描述】:

所以这适用于 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...');
        };

因非法调用而失败

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

【问题讨论】:

    标签: javascript google-chrome console.log


    【解决方案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 - 需要应用参数

    【讨论】:

    • 这不太对; console.log.apply(console, Array.prototype.call(arguments)) 可能有用。如果您执行console.log(arguments),则会将类似数组的对象arguments 传递给console.log,而不是每个实际参数。
    • 好的,修好了。 console.log.apply(console,arguments); 按原样工作。无需致电Array.prototype.call(arguments)apply() 处理 arguments 就像一个数组。
    • 很高兴,参数终于对 something 有效。在更好地支持bind 之前,这绝对是一个更好的跨浏览器解决方案。
    • 哈哈,是的。我用它所有的时间。回调真的很方便。我会做类似callback.apply( (typeof thisArg == "undefined" ? this : thisArg) , arguments ); 之类的事情,其中​​thisArg 是一个可选的范围参数。
    【解决方案2】:

    原因是当你调用IMS.putLog时,函数的this变量是IMSconsole.log 的实现可能依赖于 thisconsole

    这里有一个解决方法:

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

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

    不幸的是,这在 IE bind 在 PhantomJS 中不起作用,如果这很重要的话。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2014-02-13
      相关资源
      最近更新 更多