javascript - 代理设置一个值

标签 javascript

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/

相关文章:

javascript - 不使用 <img> 标签显示多个图像?

javascript - 有声音的新条目时的php通知

javascript - 如何使用 web3-react 将 WalletConnect 集成到您的 Dapp 中?

javascript - 从父级向子级添加特定类

javascript - 类型错误 : Cannot read properties of undefined in Vue

javascript - jQUERY 文本输入值大于10不大于5000

javascript - HTML anchor 链接 - href 和 onclick 两者?

javascript - 为(服务器端)格式化数据(客户端)

javascript - 使用 Javascript(正则表达式)查找不在 HTML 标签内的文本

javascript - 与 ng-cloak 相反,用于加载消息