var context = {};
let head;
context.head = new Proxy({}, {
get(obj, prop) {
if (!head) {
head = {
htmlAttrs: {
lang: 'Fr'
}
}
}
if (prop === 'htmlAttrs') {
return `${JSON.stringify(head.htmlAttrs)}`
}
},
set(obj, prop, value, rec) {
return Reflect.set(...arguments);
}
})
context.head.htmlAttrs = {
key: true
}
console.log(context.head.htmlAttrs)
现在它只记录 lang: 'Fr'
如何让它也记录 key: true
最佳答案
在这种情况下,get()
返回的 obj
变量包含它们:
var context = {};
let head;
context.head = new Proxy({}, {
get(obj, prop) {
if (!head) {
head = {
htmlAttrs: {
// Include the properties
...obj.htmlAttrs,
lang: 'Fr'
}
}
}
if (prop === 'htmlAttrs') {
return `${JSON.stringify(head.htmlAttrs)}`
}
const text = prop in head ? head[prop].text() : ''
return text && prop.endsWith('Attrs') ? ` ${text}` : text
},
set(obj, prop, value, rec) {
return Reflect.set(...arguments);
}
})
context.head.htmlAttrs = {
key: true
}
console.log(context.head.htmlAttrs)
关于javascript - 代理设置一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55969049/