用Proxy可以实现类似功能么?

想实现一个功能,我指定一个对象,比如

const obj = {

name: "a",

experience: [ { title: "JS", score: 34},{ title: "ES", score: 31} ],

other: {

property1: "1",

property2: "2",

property3: "3",

property4: "4",

}

}

当我给obj或者其子属性添加不存在的属性时,例如:obj.title ="wo",obj.other.property7 = "7",能够报错或者提示,又或者obj.other= { name: "1", propery1: "324"},"324"可以赋值成功,给experience可以push项。有没有比较好的思路?

回答

image.png

obj = {

name: "a",

experience: [ { title: "JS", score: 34},{ title: "ES", score: 31} ],

other: {

property1: "1",

property2: "2",

property3: "3",

property4: "4",

}

}

proxy = new Proxy(obj,{

set: function(target, property, value, receiver) {

console.log(arguments, Object.hasOwnProperty(property), Object.isPrototypeOf(property))

if(Object.hasOwnProperty(property)){

target[property] = value;

}else{

throw new Error('报错了,不存在')

}

return true

}

})

proxy.name = 'b'

console.log(obj)

proxy.name1 = 'b'

console.log(obj)

以上是 用Proxy可以实现类似功能么? 的全部内容, 来源链接: utcz.com/a/33314.html

回到顶部