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

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

问题描述

Dr 在探索 ES6 中有 const 定义. 阿克塞尔·劳施迈尔:

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

const 和 let 一样,但是你声明的变量必须是立即初始化,具有无法更改的值之后.[…]

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 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?

推荐答案

MDN 总结得很好:

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天全站免登陆