本篇探索下

  • proxy基本api => 如果上面的功能换成proxy需要怎么写呢?
  • proxy还可以做哪些事儿

proxy经常拿来与Object.defineProperty做对比,先来温故下Object.defineProperty的用法#

proxy写法

get\set\apply\construct

get\set

  1. observer({name: '', age: 0}, 'name');
  2. function observer(data, key) {
  3. let val = data[key];
  4. Object.defineProperty(data, key, {
  5. get() {
  6. console.log('getter:'+ val);
  7. return val;
  8. },
  9. set(newVal) {
  10. console.log('setter:'+ setter);
  11. val = newVal;
  12. }
  13. });
  14. }
  1. let data = {name: 'helloworld', age: 0};
  2. let newobj = new Proxy(data, {
  3. get(target, key, receiver) {
  4. console.log('get', target[key]);
  5. // return Reflect.get(target, key);
  6. return target[key];
  7. },
  8. set(target, key, value, receiver) {
  9. console.log('set', target[key], value);
  10. //return Reflect.set(target, key, value);
  11. }
  12. });
  13. newobj.name
  14. newobj.age = 2;

1、直接拦截整个对象,而不需要遍历传入key设置拦截
=== 但是 获取对象某深层属性的时候 检测到的key还是第一层key…
设置对象某深层属性的改变时 并没有检测到改变
2、生成返回新的对象,在新对象newobj操作改变才有用,旧的data上没有用

get、setter里的receiver变量

receiver ,其实接收的是一个代理对象:
receiver 输出的是当前代理对象,注意,这是一个已经代理后的对象。
image.png
当代理的对象是多层结构时,Reflect.get 会返回对象的内层结构。

apply

除此了 set、get方法还有apply方法:
apply 一般是用来拦截函数的调用,它接收三个参数,分别是目标对象、上下文对象(this)、参数数组。

  1. function test() {
  2. console.log('this is a test function');
  3. }
  4. const func = new Proxy(test, {
  5. apply(target, context, args) {
  6. console.log('hello, world');
  7. target.apply(context, args);
  8. }
  9. })
  10. func();
  11. # 通过 apply 方法可以获取到函数的执行次数,也可以打印出函数执行消耗的时间,常常可以用来做性能分析。
  12. function log() {}
  13. const func = new Proxy(log, {
  14. _count: 0,
  15. apply(target, context, args) {
  16. target.apply(context, args);
  17. console.log(`this function has been called ${++this._count} times`);
  18. }
  19. })
  20. func()

constructor

construct 方法用来拦截 new 操作符。它接收三个参数,分别是目标对象、构造函数的参数列表、Proxy 对象,最后需要返回一个对象。

function noop() {}
const Person = new Proxy(noop, {
    construct(target, args, newTarget) {
        return {
            name: args[0],
            age: args[1]
        }
    }
})
const person = new Person('tom', 21); // { name: 'tom', age: 21 }

Reflect

Reflect 核心:将obj上的内部方法如[[Get]],[[Set]] 等转移到了Relect上,用Refelct将操作转发到原对象上

好处是兼容的同时更友好
1、拥有obj上的内部方法
2、更优雅的反馈结果
Object.defineProperty(obj, name, desc)在无法定义属性时,会抛出一个错误
而Reflect.defineProperty(obj, name, desc)不会抛出错误,只是返回false。
3、让Object操作都变成函数行为
if(‘name’ in obj) ===> if(Reflect.has(obj, ‘name’))
Function.prototype.apply.call(Math.floor, undefined, [1.75]) ==> Reflect.apply(Math.floor, undefined, [1.75])
image.png
核心:用 Reflect 来将操作转发到原始对象上

在大多数情况下,使用Reflect.get(target, prop, receiver) 等效于target[prop], 但还是有些细微差别(为什么 Reflect.get 更好?)

# 当newdata2 继承自 proxydata时,会发生错误
let user = {
  _name: "Guest",
  get name() {
    return this._name;
  }
};

let admin = {
  __proto__: userProxy,
  _name: "Admin"
};

alert(admin.name); // Admin 
# 如果代理里的get是直接return target[key] 那么此时alert的是原型上的
# 所以需要 Reflect.get(target, prop, receiver); 实现完整转发

let userProxy = new Proxy(user, {
  get(target, key, receiver) { // receiver = admin
    return Reflect.get(target, key, receiver);
    // return Reflect.get(...arguments);
    // return target[key];
  }
});

receiver保证传递正确的 this 给 getter

综上return Reflect… 会提供一个安全的提示程序来转发操作,并确保我们不会忘记与此相关的任何内容。

Object.defineProperty缺陷

proxy学习笔记 - 图3

不能一次性监听对象所有属性

Object.defineProperty是针对对象的某一个key进行监听,所以解决办法是遍历所有的key依次进行监听,同时如果当前obj[key]是对象则还需递归完善监听。

而proxy可以一次性监听一个对象,无需遍历key(但是对于深层属性的更改也无法监听到,目前了解到的也是递归解决。。)

无法监听新增加的属性

let girl = {
  name: "marry",
  age: 22
}
let newgirl = 代理(girl)
newgirl.sex = '女'; // 动态添加属性 proxy可以监听到,但Object.defineProperty不行

(在 Vue 中想动态监听属性,一般用 Vue.set(girl, “hobby”, “game”) 这种形式来添加。

无法响应数组操作

Object.defineProperty 可以监听数组的变化,但无法对 push、shift、pop、unshift 等方法进行响应。
但是proxy可以
在 Vue2 和 Mobx 中都是通过重写原型实现的:

const arrayProto = Array.prototype;
const subArrProto = Object.create(arrayProto);
const methods = ['pop', 'shift', 'unshift', 'sort', 'reverse', 'splice', 'push'];
methods.forEach(method => {
    /* 监听这些方法 */
    Object.defineProperty(subArrProto, method, {
        get() {
            console.log('111')
            return (...args) => arrayProto[method].apply(this, args);
        }
    })
});
let arr = [1, 2];
arr.__proto__  = subArrProto;
arr.push(3); // 111

其他

和defineproperty劣势大部分proxy得到了解决,即proxy的优势,此外proxy的其他优势主要有:
1、多达13种拦截方法,不限于apply、ownKeys、deleteProperty、has等等是Object.defineProperty不具备的
2、Proxy返回的是一个新对象,我们可以只操作新的对象达到目的,而Object.defineProperty只能遍历对象属性直接修改。

proxy妙用

核心思路:重写属性获得的操作,使得在获得属性的时候可以额外做点什么 或者 重新决定返回什么

属性链式调用

利用 Proxy,可以将读取属性的操作(get),转变为执行某个函数,从而实现属性的链式操作。

var double = n => n * 2;
var pow    = n => n * n;
var reverseInt = n => n.toString().split("").reverse().join("") | 0;

pipe(3).double.pow.reverseInt.get; // 63
=> 3*2 = 6 => 6^2 = 36 => 63

# 实现
var pipe = function (value) {
  var funcStack = [];
  var oproxy = new Proxy({} , {
    get : function (pipeObject, fnName) {
      if (fnName === 'get') {
        return funcStack.reduce(function (val, fn) {
          return fn(val);
        },value);
      }
      funcStack.push(window[fnName]);
      return oproxy;
    }
  });

  return oproxy;
}

深层属性安全获取

通常写法:
let name = obj && obj.person ? obj.person.name : null;

# 代理后
get(obj)() === obj; // true
get(obj).person.name(); // undefined
get(obj).person.name.xxx.yyy.zzz(); // undefined


# 实现
 let isFirst = true;
    function noop() {}
    let proxyVoid = get(undefined);
    function get(obj) {
        if (obj === undefined) {
            if (!isFirst) {
                return proxyVoid;
            }
            isFirst = false;
        }
        // 注意这里拦截的是 noop 函数
        return new Proxy(noop, {
            // 这里支持返回执行的时候传入的参数
            apply(target, context, [arg]) {
                return obj === undefined ? arg : obj;
            },
            get(target, prop) {
                if (
                    obj !== undefined &&
                    obj !== null &&
                    obj.hasOwnProperty(prop)
                ) {
                    return get(obj[prop]);
                }
                return proxyVoid;
            }
        })
    }
    this.get = get;

get拦截

简单的语法实现复杂的返回:
通用dom生成器

const el = dom.div({},
  'Hello, my name is ',
  dom.a({href: '//example.com'}, 'Mark'),
  '. I like:',
  dom.ul({},
    dom.li({}, 'The web'),
    dom.li({}, 'Food'),
    dom.li({}, '…actually that\'s it')
  )
);

document.body.appendChild(el);

=== dom 实际是一个被proxy代理的对象 调用dom的属性get会返回目标dom ===
const dom = new Proxy({}, {
  get(target, property) {
    return function(attrs = {}, ...children) {
      const el = document.createElement(property);
      for (let prop of Object.keys(attrs)) {
        el.setAttribute(prop, attrs[prop]);
      }
      for (let child of children) {
        if (typeof child === 'string') {
          child = document.createTextNode(child);
        }
        el.appendChild(child);
      }
      return el;
    }
  }
});

代理类

实现 在 类 实例化的时候 和 调用某些方法的时候 统一做一些事,比如: 实现某方法执行的执行时间计数。
类似于 Aop 但是是基于代理实现

const MyClass = proxyTrack(Person);
const myClass = new MyClass('tom', 21);
myClass.say();
myClass.name;

# 内部实现
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  say() {
    console.log(`my name is ${this.name}, and my age is ${this.age}`)
  }
}
const proxyTrack = (targetClass) => {
  const prototype = targetClass.prototype;
  Object.getOwnPropertyNames(prototype).forEach((name) => {
        targetClass.prototype[name] = new Proxy(prototype[name], {
            # 拦截函数的调用
            apply(target, context, args) {
                console.time();
                target.apply(context, args);
                console.timeEnd();
            }
        })
  })

  return new Proxy(targetClass, {
    # 拦截 construct 方法
    construct(target, args) {
      const obj = new target(...args);
      # 返回代理过的对象
      return new Proxy(obj, {
        get(target, prop) {
              console.log(`${target.name}.${prop} is being getting`);
              return target[prop]
        }
      })
    }
  })       
}

参考

es6-阮一峰
ES6 Proxy 可以做哪些有意思的事情?
面试官: 实现双向绑定Proxy比defineproperty优劣如何?