编程语言
首页 > 编程语言> > Javascript-为什么在if()或try {} catch(e){}内部时const在多次运行代码时引发错误?

Javascript-为什么在if()或try {} catch(e){}内部时const在多次运行代码时引发错误?

作者:互联网

我正在尝试使用const声明一堆常量.我的问题是,在Firebug控制台中测试代码会引发错误,抱怨“ const foo的重新声明”.

我曾尝试将其包装在try {} catch(e){}块中,但这无济于事,甚至在尝试使用以下代码来解决它时(发布减去所有console.info()“ debugging”需要澄清),第二次运行时仍会引发错误:

if(!chk_constsDeclaredYet) {
  var chk_constsDeclaredYet = true;
  const foo="bar";
}

我的问题是,当const位于if(){}中时,当第二次运行代码时,为什么还要查看const foo?

注意:代码将在firebug javascript控制台中运行,而我想要实现的工作流程是:

>将代码粘贴到Firebug控制台中
>命中运行(创建常量)
>我在不重新加载页面的情况下对控制台中的代码进行了编辑(常量仍在页面上下文中定义)
>再次命中运行(使用if(){}以避免在先前运行中已声明常量的情况下重新声明常量)
>从(3)开始重复

萤火虫输出:

//FIRST RUN::
>>> console.group() console.info('--code start--'); ...console.info('--code end--'); console.groupEnd()
--code start--
chk_constsDeclaredYet = undefined
foo = undefined
--if()--
--if() running..--
--end if()--
chk_constsDeclaredYet = true
foo = bar
--code end--

//SECOND RUN::
>>> console.group() console.info('--code start--'); ...console.info('--code end--'); console.groupEnd()
TypeError: redeclaration of const foo { message="redeclaration of const foo", more...}

解决方法:

这是一个古老的答案.我写了一个slightly newer answer,处理类似的“ const re-assignment / scope”(常量重新分配/作用域)问题,在该问题中,我发现所产生的错误(如果存在)会因执行方法和浏览器而异.

由于const(不属于ECMAScript 5th版标准的一部分)在ECMAScript 6th版中具有不同的含义,因此我建议在当前代码中避免使用它.

像var这样的const是“作用域”的.我怀疑问题是由与var发生的绑定相同的“功能扩展”提升引起的(这解释了为什么异常不是来自赋值而是来自声明).也就是说,任何后续的const x = …,无论它们出现在哪里,都被视为无效,因为先前的声明已经存在(根据定义,每个作用域只能有一个给定名称的const).但是,const可以取任何值,因此赋值发生在const x = …站点,就像赋值发生在var x = …站点一样,即使注释/绑定被提升到范围.

这是一个简单的测试用例,可以更清楚地说明问题:

function x () { if (true) { const a = 1 } else { const a = 2 }}
// => TypeError: redeclaration of const a @ <x-jsd:interactive-session

如您所见,错误发生在函数声明而不是函数执行时.这就是为什么try / catch不起作用的原因.行为也可能会受到您正在使用的交互工具的影响,具体取决于其执行代码的方式(例如,每次都具有相同的执行上下文吗?).

但是,这很好用,并加强了上面的初始主张:

(function x() { if (false) { const c = 1 }; return c })()
// => undefined

https://developer.mozilla.org/en/JavaScript/Reference/Statements/const

(添加了粗体字)

Creates a constant that can be global or local to the function in which it is declared. Constants follow the same scope rules as variables.

The value of a constant cannot change through re-assignment, and a constant cannot be re-declared. Because of this, although it is possible to declare a constant without initializing it, it would be useless to do so.

A constant cannot share its name with a function or a variable in the same scope.

const is a Mozilla-specific extension, it is not supported by IE, but has been partially supported by Opera since version 9.0 and Safari.

标签:const,constants,firebug,javascript
来源: https://codeday.me/bug/20191023/1915125.html