const obj1 = Object.freeze({
a: 1,
})
obj1.a = 2 // 不能修改
Object.deepFreeze = function (obj){
var propNames = Object.getOwnPropertyNames(obj);
propNames.forEach(name => {
var prop = obj[name];
if (typeof prop == 'object' && prop !== null) {
Object.deepFreeze(prop)
}
})
return Object.freeze(obj)
}
const obj1 = Object.deepFreeze({
a: {
b: {
c: 1,
d: [1, 2, 3],
},
},
})
obj1.a.b.c = 2
obj1.a.b.d[1] = 5
console.log(obj1.a.b.c) // 1
console.log(obj1.a.b.d) // [1, 2, 3]
网友评论