代理和反射

1. Proxy代理

Proxy可以理解成,在目标对象之前架设一层“拦截”,外界对该对象的访问,都必须先通过这层拦截,因此提供了一种机制,可以对外界的访问进行过滤和改写。

Proxy这个词的原意是代理,用在这里表示由它来“代理”某些操作,可以译为“代理器”。

语法

new Proxy(被代理对象,处理函数)

处理函数是规定的一些方法:

  "get": function (oTarget, sKey) {
    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
  },
  "set": function (oTarget, sKey, vValue) {
    if (sKey in oTarget) { return false; }
    return oTarget.setItem(sKey, vValue);
  },
  "deleteProperty": function (oTarget, sKey) {
    if (sKey in oTarget) { return false; }
    return oTarget.removeItem(sKey);
  },
  "enumerate": function (oTarget, sKey) {
    return oTarget.keys();
  },
  "ownKeys": function (oTarget, sKey) {
    return oTarget.keys();
  },
  "has": function (oTarget, sKey) {
    return sKey in oTarget || oTarget.hasItem(sKey);
  },
  "defineProperty": function (oTarget, sKey, oDesc) {
    if (oDesc && "value" in oDesc) { oTarget.setItem(sKey, oDesc.value); }
    return oTarget;
  },
  "getOwnPropertyDescriptor": function (oTarget, sKey) {
    var vValue = oTarget.getItem(sKey);
    return vValue ? {
      "value": vValue,
      "writable": true,
      "enumerable": true,
      "configurable": false
    } : undefined;
  },
    construct: function(oTarget, args){},
    apply: function(oTarget, that, args){},

https://www.jb51.net/article/132373.htm

2. reflect 反射

https://blog.csdn.net/lihaoen666/article/details/78112869

代理和反射结合使用可以实现数据的双向绑定,vue3就使用这种方式实现双向绑定的

原文地址:https://www.cnblogs.com/wenwenli/p/9366926.html