在javascript和谐/ ECMAScript 6中删除或覆盖const变量 [英] delete or override const variables in javascript Harmony / ECMAScript 6

查看:1036
本文介绍了在javascript和谐/ ECMAScript 6中删除或覆盖const变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读和修改ECMAScript 6提供的新功能。



用于编写常量变量的新const语句是一个漂亮的功能,它将功能添加到已经有趣的更新。



变量创建为只读,一旦声明就不能被覆盖。



编辑:出现问题,例如,在控制台上测试代码时。运行包含一个const定义的脚本两次,会导致一个错误,打破执行。



如果我想发布那个关键字怎么办?有没有办法取消设置或删除变量?



我已阅读这篇文章,这实际上也是影响 var 语句的问题,因为创建变量的环境在许多方面是不同的抽象层次。



ECMAScript 6如何打算解决这个问题?

解决方案

不可能重新定义使用 const 声明的变量。



但是, const 是块范围的。为了解决您所描述的问题,当测试控制台中的一些代码时,您需要做的是将脚本包装到 {}

  {const x = 1; } 
{const x = 2;请注意,许多浏览器已经支持 const $ / code $ c>关键字还没有支持块范围的常量,所以上面的例子会在Chrome和Firefox中失败(请参阅 Kangax的兼容性表了解更多)。


Reading and tinkering with the new features offered by ECMAScript 6.

The new 'const' statement for writing constant variables is a nifty feature, which adds features to an already interesting update.

The variable is created as read-only, and once it is stated it can't be overridden.

EDIT: A consequent problem arise, for example, when testing code on the console. Running a script containing a const definition twice, would lead to an error, breaking the execution.

What if I want to release that keyword? Is there any way to unset or delete the variable?

I've read in this post that this is actually a problem which affects the var statement as well, because the environments where the variables are created are different on many level of abstraction.

How ECMAScript 6 intend to address this issue?

解决方案

It is not possible to redefine variables declared using const.

However, const is block-scoped. To address the issue you describe, when testing some code in the console all you would have to do is wrap your script in { and }:

{ const x = 1; }
{ const x = 2; }

Note that many browsers that already support the const keyword do not yet support block-scoped constants so the example above will fail in Chrome and Firefox (See Kangax's compatibility table for more).

这篇关于在javascript和谐/ ECMAScript 6中删除或覆盖const变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆