let obj ={
say:'hai',gethello(){returnthis.say +' world'},sethello(val){this.say = val
}}
console.log(obj.hello);// hai world
obj.hello ='hello'
console.log(obj.hello);// hello world
Object.defineProperty
let obj ={ a:'hello'}let cloneObj =JSON.parse(JSON.stringify(obj))// 注意返回不能直接用 obj,否则陷入 get 死循环
Object.keys(obj).forEach(key =>{
Object.defineProperty(obj, key,{get(){
console.log(cloneObj[key])return cloneObj[key]},set(val){
cloneObj[key]= val
}})})
obj.a // hello
obj.a ='world'
obj.a // world