简体   繁体   中英

redeclaration of var console

I'm using Hoptoad to get error reports of my JavaScript and recently I got this error:

redeclaration of var console

the backtrace is not very useful:

internal: :

:0:in `{anonymous}()'

and I know it happened on "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.16) Gecko/20110323 Ubuntu/10.10 (maverick) Firefox/3.6.16" but I can't figure out how console would be re-declared. Do you have any ideas? Here's how I declare console:

if (typeof console == "undefined") {
  var console = {
    log: function() {
    }
  };
}

You can't conditionally declare variables. Declarations are parsed and added as properties of the activation object before any code is executed. Your code is equivalent to:

var console;
if (typeof console == "undefined") {
  console = {
    log: function() {
    }
  };
}

This is also called "hoisting" (not a term I'm fond of) as declarations are effectively "hoisted" to the top of the function or above any other code.

Declaring a variable more than once in the same function or scope is harmless, but it indicates possible misunderstanding of scope (eg expecting block scope) or unintended reuse of an identifier.

Please edit this to confirm or deny this part:

The way to do it is by re-definig window.console:

if (typeof window.console == "undefined") {
  window.console = {
    log: function() {
    }
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM