本文介绍了如何使用javascript代理嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在js bin中有这个代码:
I have this code in js bin:
var validator = {
set (target, key, value) {
console.log(target);
console.log(key);
console.log(value);
if(isObject(target[key])){
}
return true
}
}
var person = {
firstName: "alfred",
lastName: "john",
inner: {
salary: 8250,
Proffesion: ".NET Developer"
}
}
var proxy = new Proxy(person, validator)
proxy.inner.salary = 'foo'
如果我做 proxy.inner.salary = 555;
它不起作用。
但是如果我做 proxy.firstName =Anne
,那么效果很好。
However if i do proxy.firstName = "Anne"
, then it works great.
我不明白为什么它不起作用递归。
I do not understand why it does not work Recursively.
推荐答案
您可以添加获取
陷阱并返回一个新的代理,其中 validator
作为处理程序:
You can add a get
trap and return a new proxy with validator
as a handler:
var validator = {
get(target, key) {
if (typeof target[key] === 'object' && target[key] !== null) {
return new Proxy(target[key], validator)
} else {
return target[key];
}
},
set (target, key, value) {
console.log(target);
console.log(key);
console.log(value);
return true
}
}
var person = {
firstName: "alfred",
lastName: "john",
inner: {
salary: 8250,
Proffesion: ".NET Developer"
}
}
var proxy = new Proxy(person, validator)
proxy.inner.salary = 'foo'
这篇关于如何使用javascript代理嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!