声明变量const只能防止其值被新值替换。const对对象的内部状态没有任何限制。下例显示,const可以更改对象的属性值,甚至可以添加新的属性,因为分配给对象的对象person是修改的,但不能替换。
const person = { name: "John" }; console.log('The name of the person is', person.name); person.name = "Steve"; console.log('The name of the person is', person.name); person.surname = "Fox"; console.log('The name of the person is', person.name, 'and the surname is', person.surname);
结果:
The name of the person is John The name of the person is Steve The name of the person is Steve and the surname is Fox
在此示例中,我们创建了名为的常量对象,person并重新分配了person.name属性并创建了新person.surname属性。