May 30, 2021 Article blog
It is well known that element objects can use the parentNode property to access their parent element.
Sometimes we want JavaScript objects to have access to the parent object of a property.
We can refer to document practices
The parentNode property is automatically generated when an object is created to point to its parent
Use The Proxy() ProvideD By ES6 To Represent The Official Document For Object
AssignmentS().
function mObj(Obj) {
var obj = new Proxy(Obj, {
set: function (obj, pro, val, Pro) {
if (typeof val == 'object') {
val.parent = Pro
val = mObj(val)
}
obj[pro] = val
return val
}
})
return obj
}
We just need to use the mObj method to initialize the objects we need to represent
var obj = mObj({})
concentrate! Only empty objects can be added, otherwise their properties will lose agents
obj.a = {}
obj.b = {}
obj.a.aa = {}
obj.b.bb = {}
console.log(obj) // Proxy {a: Proxy, b: Proxy}
Proxy is the proxy object
console.log(obj.a.parent,obj.b.parent)
// Proxy {a: Proxy, b: Proxy} Proxy {a: Proxy, b: Proxy}
console.log(obj.a.aa.parent,obj.b.bb.parent)
// Proxy {parent: Proxy, aa: Proxy} Proxy {parent: Proxy, bb: Proxy}
You can see that the parent of the property has been successfully acquired so what can it be used for?
obj.a.parent // Proxy {a: Proxy, b: Proxy}
var p = obj.a
p.parent.c = {}
obj.c // Proxy {parent: Proxy}
var p1 = obj.a.parent, p2 = obj.b.parent
var p3 = obj.a.aa.parent, p4 = obj.b.bb.parent
p1 == p2 // true
p3 == p4 // false
p5 = obj.a.aa
while(p5.parent) {
p5 = p5.parent
}
p5 // Proxy {a: Proxy, b: Proxy}
p5 == obj // true