如何在 ES6 中取消设置 Javascript 常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31291436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unset a Javascript Constant in ES6?
提问by Laxmikant Dange
I read thispost, using delete
keyword, we can delete JavaScript variable. But when I tried the same operations with constant but it is returning false when I try to delete constant. Is there any way to delete constants from memory?
I tried thisanswer but its also not working.
我读了这篇文章,使用delete
关键字,我们可以删除 JavaScript 变量。但是,当我尝试对常量执行相同的操作时,但是当我尝试删除常量时它返回 false。有没有办法从内存中删除常量?我试过这个答案,但它也不起作用。
采纳答案by Toni Leigh
You can't directly do it, looking at the specs show us that the value can be set, but not over-written (such is the standard definition of a constant), however there are a couple of somewhat hacky ways of unsetting constant values.
您不能直接这样做,查看规范向我们表明该值可以设置,但不能被覆盖(这是常量的标准定义),但是有几种方法可以取消设置常量值.
Using scope
使用范围
const
is scoped. By defining the constant in a block it will only exist for this block.
const
是范围的。通过在块中定义常量,它将只存在于该块中。
Setting an object and unsetting keys
设置对象和取消设置键
By defining const obj = { /* keys */ }
we define a value obj
that is constant, but we can still treat the keys like any other variable, as is demonstrated by the examplesin the MDN article. One could unset a key by setting it to null.
通过定义,const obj = { /* keys */ }
我们定义了一个obj
常量,但我们仍然可以像对待任何其他变量一样对待键,如MDN 文章中的示例所示。可以通过将键设置为 null 来取消设置键。
If it's memory managementthat is the concern then both these techniques will help.
如果关注的是内存管理,那么这两种技术都会有所帮助。
回答by Felix Kling
The delete
operator is actually for deleting an object property, not a variable. In fact, in strict mode, delete foo
is a syntax error.
该delete
运算符实际上是用于删除对象属性,而不是变量。其实在严格模式下,delete foo
就是语法错误。
Usually you can "delete" a value/object by removing all references to it, e.g. assigning null
to a variable.
通常您可以通过删除对它的所有引用来“删除”一个值/对象,例如分配null
给一个变量。
However, since constants are not writable (by definition) there is no way to do this.
但是,由于常量不可写(根据定义),因此无法做到这一点。
回答by Roumelis George
As I wrote on my comment, delete can only be used on objects and arrays. So, what you can actually do is store all your constants in a constant object and free up memory by deleting it's properties, like this:
正如我在评论中所写,删除只能用于对象和数组。因此,您实际上可以做的是将所有常量存储在一个常量对象中,并通过删除它的属性来释放内存,如下所示:
const myConstants = {};
myConstants.height = 100;
delete myConstants.height;