在 javascript 中,我們可以使用點符號向物件添加新屬性
const obj = {}
obj.a = "hello"
console.log(obj) // prints { a: "hello" }
但是,使用點表示法無法將屬性添加到尚不存在的物件
obj.a.b = "hello" // <-- cannot set properties of undefined (setting 'b')
obj.a = { b: "hello" } // <-- OK
我想實作這種行為
const obj = {}
obj.a.b = "hello"
console.log(obj) // prints { a: { b: "hello" } }
我的想法
我能想到的唯一可以接近這一點的就是使用代理
const obj = new Proxy({}, {
set(target, key, receiver) {
// if a.b could make it here before the error is thrown, i'd handle this
// btw, this means that "key" should contain [a,b] which is not how this works.
}
})
obj.a.b = "hello"
代理的想法行不通,可能絕對沒有辦法像我問的那樣改變 JS 的本機行為,但也許我錯過了一些東西?
uj5u.com熱心網友回復:
代理確實有效。您需要使用get陷阱而不是set:
const obj = new Proxy({}, {
get(target, key, receiver) {
if (!(key in target)) return (target[key] = {});
return Reflect.get(target, key);
},
});
obj.a.b = "hello";
console.log(obj);
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/504514.html
標籤:javascript 目的
上一篇:合并多個物件(es5)
