var 控制台的重新声明
我正在使用 Hoptoad 来获取 JavaScript 的错误报告,最近我收到此错误:
重新声明 var console
回溯不是很有用:
internal: :
:0:in `{anonymous}()'
我知道它发生在“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”,但我不知道如何重新声明控制台。你有什么想法吗?这是我声明控制台的方式:
if (typeof console == "undefined") {
var console = {
log: function() {
}
};
}
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() {
}
};
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能有条件地声明变量。在执行任何代码之前,声明将被解析并添加为激活对象的属性。您的代码相当于:
这也称为“提升”(不是我喜欢的术语),因为声明实际上被“提升”到函数的顶部或任何其他代码之上。
在同一函数或作用域中多次声明变量是无害的,但它表明可能对作用域产生误解(例如期望块作用域)或标识符的意外重用。
请编辑此内容以确认或拒绝此部分:
方法是重新定义 window.console:
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:
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 (e.g. 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: