Sogrey / Web-QA

https://sogrey.github.io/Web-QA/
MIT License
6 stars 2 forks source link

如何在js"深冻结"对象? #296

Open Sogrey opened 4 years ago

Sogrey commented 4 years ago

如果咱们想要确保对象被深冻结,就必须创建一个递归函数来冻结对象类型的每个属性:

没有深冻结

let person = {
    name: "Leonardo",
    profession: {
        name: "developer"
    }
};
Object.freeze(person); 
person.profession.name = "doctor";
console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }

深冻结

function deepFreeze(object) {
    let propNames = Object.getOwnPropertyNames(object);
    for (let name of propNames) {
        let value = object[name];
        object[name] = value && typeof value === "object" ?
            deepFreeze(value) : value;
    }
    return Object.freeze(object);
}
let person = {
    name: "Leonardo",
    profession: {
        name: "developer"
    }
};
deepFreeze(person);
person.profession.name = "doctor"; // TypeError: Cannot assign to read only property 'name' of object