1.Object.defineProperty(target, property,desc )
const obj = {a: 1,b:2}
Object.defineProperty(obj,'c',{value:3})
console.log(obj) // {a: 1,b:2,c: 3}
2.Proxy(target, handler) 不仅可以对对象还可以对数组进行修改
const obj = {a: 1,b:2}
const proxyValue = new Proxy(obj,{
get: (target, propKey, receiver)=>{
return Reflect.get(target, propKey, receiver)
},
set: (target, propKey, value, receiver)=>{
return Reflect.set(target, propKey, value, receiver)
}
})
proxyValue.c = 3
console.log(proxyValue) // {a: 1,b:2,c:3}
const arr = [{a: 1},{b:2}]
const proxyValue = new Proxy(arr,{
get: (target, propKey, receiver)=>{
return Reflect.get(target, propKey, receiver)
},
set: (target, propKey, value, receiver)=>{
return Reflect.set(target, propKey, value, receiver)
}
})
proxyValue.push({d:343}) // [{a: 1},{b:2},{d:343}]