我应该在ES2015中声明一个可变数组/对象作为一个const吗? [英] Should I declare a mutable array/object as a const in ES2015?

查看:97
本文介绍了我应该在ES2015中声明一个可变数组/对象作为一个const吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果它是一个不可变的对象,那么我毫不怀疑将它声明为一个const。
但是在这种情况下,它只是一个对象的const引用,而该对象稍后在代码中被修改。

  const styles = {}; 
...
styles.width = rect.width +'px';

我很害怕读取此代码的开发人员会感到困惑。
感觉像 let 更适合变异的对象。

解决方案

这可能是一个问题,你将无法得到最终的答案,因为它是非常基于意见的。



一点点的历史背景可以帮助您了解混淆的 const 是否位于第一位:



EcmaScript规范前编辑Allan Wirfs-Brock自己说:


在一个稍微不同(也许更好)的宇宙中,ECMAScript const 声明将被命名为 let 并引入SSA绑定。


并问,为什么不是这样,他回复


let / const是ES4的结转提案和Moz JS1.7



TC39从未认真探索过命名替代方案


所以你可以说 const 是一个不正确的词,因为它不会做什么不熟悉的人可能会期望它做。



由于 const 以它的方式工作,几乎肯定不会改变,我仍然会定义你的对象与 const



这可能有助于不熟悉

也许这可能有助于在第一次出现时添加评论const 与一个对象,沿着以下行:

  //重要提示:'const'只能确保'style'总是引用同一个对象,
//它不会使它变得不可变
const styles = {};

意见可能会有所不同。


If it was an immutable object, then I would have no doubt in declaring it as a const. But in this case it's just a const reference to an object while the object is modified later in the code.

const styles = {};
...
styles.width = rect.width + 'px';

I'm afraid it will be confusing for developers reading this code. It feels like let is more appropriate for objects that get mutated.

解决方案

This is probably a question you wont be able to get a final answer for, as it is very opinion-based.

A little bit of historical background can help to understand how the confusing const came to be in the first place:

Allan Wirfs-Brock, the former editor of the EcmaScript spec, himself said:

In a slightly different (and perhaps better) universe, ECMAScript const declaration would be named let and introduce a SSA binding.

And asked, why this was not the case, he responded:

let/const was a carry over from ES4 proposals and Moz JS1.7

TC39 never seriously explored naming alternatives

So you could say const is a bit of a misnomer, since it doesn't do what people who aren't familiar with it might expect it to do.

Since const works the way it does though and is almost certainly not going to change, I would still define your objects with const.

This might help people who are unfamiliar with the way const works to get a better understanding.

Maybe it could help to add a comment at the first occurrence of const with an object, along the lines of:

// Important: 'const' only ensures that 'styles' always references the same object,
// it does not render it immutable
const styles = {};

Opinions may vary though.

这篇关于我应该在ES2015中声明一个可变数组/对象作为一个const吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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