前置知识
作用域
const对象怎么禁止修改
- 方法一: Object.freeze
- 方法二:defineProperty+递归,对于每个节点都有:writable:false
javascript">const obj={a1:{b1:{c1:'c1'}},a2:{b1:{c1:'c2'},b2:[]},
}// solution1: Object.freeze(obj)
// Object.freeze(obj);
// obj.a2="new"
// console.log(obj)function myFoo(obj){if(!obj){return;}Object.keys(obj).forEach(key=>{if(typeof obj[key]==="object"){Object.defineProperty(obj,key,{writable:false});myFoo(obj[key]);}});
}myFoo(obj);
obj.a2="new"
console.log(obj)