用javascript常量注意到这种行为......看起来const
关键字在处理对象时失去了不变性。
想知道您对此行为的看法吗?
const fruits = 'banana';
fruit = 'apple';
console.log(fruit); // 'banana' as expected
//----------------------------------------------------------------------
const fruit = ['apple'];
fruit.push('banana');
console.log(fruit); // ['apple', 'banana'] ???????
fruit = 'anything';
console.log(fruit); // ['apple', 'banana'] as expected;
//----------------------------------------------------------------------
const brands = {};
brands = [];
console.log(brands); // {} as expected
brands.sony = "playstation"
console.log(brands); // {sony:'playstation'} ???????
答案 0 :(得分:3)
作为Java常量的Javascript常量是不可变的。但是你必须将它们视为价值的指针。它们总是指相同的值。该值可以是原始值或对象。因此,您无法更改对另一个对象的引用,但您可以修改该对象(如果它是可修改的,则不能修改原始类型)。
const TEST={ name: 'myObject'}
TEST= ... // this always does nothing, the current reference cannot be changed
TEST.name=... //this changes the state of the current reference.
@Jess'回答为您提供了使对象无法修改的方法。
答案 1 :(得分:1)
Object.freeze
和Object.seal
将介绍您正在寻找的功能。这两种方法都会阻止添加新属性或删除现有属性,而前者也会阻止正在编辑的现有属性。
我喜欢当前使用const
,例如在文件顶部声明大型模块或命名空间时。它只是对整个被覆盖的一点保护,同时仍让你进行互动。