Print

Object.freeze() 和 const 的区别是什么?


作者: 文章来源:

本文原地址:https://www.mimiwuqi.com/webqianduan/197410.html

const和Object.freeze是两个完全不同的概念。

const 声明一个只读的变量,一旦声明,常量的值就不可改变:

const person = {
    name: "mybj"
};
let animal = {
    species: "snake"
};
person = animal; // ERROR "person" is read-only

Object.freeze适用于值,更具体地说,适用于对象值,它使对象不可变,即不能更改其属性。

let person = {
    name: "Mybj"
};
let animal = {
    species: "snake"
};
Object.freeze(person);
person.name = "Lima"; //TypeError: Cannot assign to read only property 'name' of object
console.log(person);

推荐阅读:Object.seal 和 Object.freeze 方法之间有什么区别?

更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/