使用 const 我们仍然可以修改 javascript 对象的内容,但对该对象的引用将是不可变的。
const product = {name: "sugar", weight: "1 kg"}; product.name = "some new name"; console.log(product);
{ name: "some new name", weight: "1 kg" }
当我们不想修改对象的内容时,首选使用 freeze。
const product = {name: "sugar", weight: "1 kg"}; object.freeze(product); product.name = "some new name"; console.log(product);
{ name: "Sugar", weight: "1 kg" }