Internet Explorer: “console is not defined” Error

前端 未结 9 1601
天涯浪人
天涯浪人 2020-12-05 18:33

I was using console.log() in some JavaScript I wrote and an error of: console is not defined was thrown in Internet Explorer (worked fine in other

相关标签:
9条回答
  • 2020-12-05 19:05

    Edit of @yckart's answer

    Using c.length as input to a function which defines c won't work. Also you're just reassigning items in the array with noop when you should be adding methods to window.console.

    (function(w){
      var c = 'assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn'.split(','),
      noop = function () {};
    
      w.console = w.console || (function (len) {
        var ret = {};
        while (len--) { ret[c[len]] = noop; }
        return ret;
      }(c.length));
    })(window);
    
    0 讨论(0)
  • 2020-12-05 19:11

    Inspired by @Edgar Villegas Alvarado answer, completed the methods and made it a bit simpler:

    (function(w){
      var c = 'assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn'.split(','),
      noop = function () {};
    
      w.console = w.console || (function (len) {
        var ret = {};
        while (len--) { ret[c[len]] = noop; }
        return ret;
      }(c.length));
    })(window);
    

    Edited to put into an IIFE and fix a syntax error!

    0 讨论(0)
  • 2020-12-05 19:15

    This is a funny thing about undeclared variables. The JS engine tries to resolve the variable to a property of window. So usually, foo == window.foo.

    But, if that property does not exist, it throws an error.

    alert(foo); // Syntax error: foo is not defined
    

    (Should be "foo is not declared" imho, but whatever.) That error does not occur when you explicitly reference the window's property:

    alert(window.foo); // undefined
    

    ...or declare that variable:

    var foo;
    alert(foo); // undefined
    

    ...or use it for initialization:

    foo = 1; // window.foo = 1
    

    The strange thing is that the typeof operator also prevents this error:

    alert(typeof foo); // "undefined"
    

    So, to sum things up: You cannot use undeclared variables in expressions unless there's a property of window with the same name, or you use it as an operand of typeof. In your example, window.console does not exist, and there's no var declaration. That's why you get an error.

    0 讨论(0)
提交回复
热议问题