代理设定值

时间:2019-05-03 11:36:33

标签: 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

1 个答案:

答案 0 :(得分:1)

在这种情况下,obj返回的get()变量包含它们:

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)