源码https://github.com/tj/node-delegates

委托模式

将内部属性委托给外部处理

安装

  1. npm i delegates

使用

  1. const delegate = require('delegates');
  2. const proto = {
  3. dog: {
  4. name: '旺财',
  5. age: 1,
  6. sex: '男',
  7. bar() {
  8. console.log('bar!');
  9. }
  10. },
  11. }
  12. // 将内部对象 dog 的属性、函数
  13. // 委托至暴露在外的 Shop 上
  14. delegate(proto, 'dog')
  15. // proto.dog.name属性委托到 proto上 可以直接proto.name只读。
  16. .getter('name')
  17. // proto.dog.age属性委托到 proto上 可以直接proto.age只写。
  18. .setter('age')
  19. // proto.dog.sex属性委托到 proto上 可以直接proto.sex写读可写
  20. .access('sex')
  21. // proto.dog.bar方法委托到 proto上 可以直接proto.bar调用
  22. .method('bar');

源码

源码很简单:

  • method是通过call实现的
  • getter是通过defineGetter实现的
  • setter是通过defineSetter实现的
  • access是通过getter+setter上实现的
  • fluent是在外部对应属性挂一个方法,方法调用时如果有入参就设置对应属性的值,如果没入参就返回当前属性的值