关键字'const'不会使该值不可变。这是什么意思? [英] Keyword 'const' does not make the value immutable. What does it mean?

查看:204
本文介绍了关键字'const'不会使该值不可变。这是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

探索ES6 中有常规定义 。Axel Rauschmayer:

There's the const definition in Exploring ES6 by Dr. Axel Rauschmayer:


const 像let一样工作,但你声明的变量必须be
立即初始化,的值不能更改
之后
。 [...]

const works like let, but the variable you declare must be immediately initialized, with a value that can’t be changed afterwards. […]

const bar = 123;
bar = 456;  // TypeError: `bar` is read-only


然后他写了


陷阱:const不使值不可变

const 只意味着变量始终具有相同的值
,但并不意味着该值本身是或不可变的。

const only means that a variable always has the same value, but it does not mean that the value itself is or becomes immutable.

我很困惑这个陷阱。这个陷阱可以清楚地定义 const

I am little confused with this pitfall. Can any one clearly define the const with this pitfall?

推荐答案

一个href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const =noreferrer> MDN 很好地总结:

MDN sums it up nicely:


const声明为值创建只读引用。这并不意味着它所持有的值是不可变的,只是变量标识符不能重新分配。例如,如果内容是一个对象,这意味着对象本身仍然可以被修改。

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in case the content is an object, this means the object itself can still be altered.

更简洁:const创建一个不可变的约束力。

More succinctly: const creates an immutable binding.

换句话说:const,像var,给你一个可变的内存块,你在其中存储东西。但是,const指示您必须继续引用相同的内存块 - 您不能将变量重新分配给不同的内存块,因为变量引用是常量。

In other words: const, like var, gives you a mutable chunk of memory in which you're storing something. However, const dictates that you must keep referring to that same chunk of memory – you can't reassign the variable to a different chunk of memory, because the variable reference is constant.

为了真正使一些不变且不变的声明,您需要使用类似 Object.freeze()的东西。但是,这很浅,只适用于键/值对。冻结整个对象需要更多的努力。以表现方式反复进行这样做还有一个挑战。如果您真的有需要,我建议您查看一些类似 Immutable.js 的内容

To really make something constant and unchanging after you've declared it, you need to use something like Object.freeze(). However, that's shallow and only works on key/value pairs. Freezing an entire object takes a bit more effort. To do so repeatedly in a performant way is yet more challenging. If you really have a need for that, I'd recommend checking out something like Immutable.js

这篇关于关键字'const'不会使该值不可变。这是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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