简体   繁体   English

var控制台的重新声明

[英]redeclaration of var console

I'm using Hoptoad to get error reports of my JavaScript and recently I got this error: 我正在使用Hoptoad来获取我的JavaScript的错误报告,最近我收到了这个错误:

redeclaration of var console var控制台的重新声明

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. 我知道它发生在“Mozilla / 5.0(X11; U; Linux x86_64; zh-CN; rv:1.9.2.16)Gecko / 20110323 Ubuntu / 10.10(特立独行)Firefox / 3.6.16”但我无法弄清楚如何重新声明控制台。 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: 这样做的方法是重新定义window.console:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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