node delegates解析及koa中应用

这是一个用来提升内部属性上的方法或者属性的包,换句话说就是把对象内部的属性暴露到根属性上。

原理:通过原型链继承达到效果

API

Delegate(proto, prop)

用于创建一个 delegator 实例,用于把 proto 接收到的一些操作委托给它的 prop 属性进行处理。

Delegate.auto(proto, targetProto, targetProp)

根据 targetProp 所包含的键,自动判断类型,把 targetProto 上的对应属性代理到 proto。可以是 getter、setter、value 或者 method。

Delegate.prototype.method(name)

在 proto 对象上新增一个名为 name 的函数,调用该函数相当于调用 proto 的 prop 属性上的 name 函数。

Delegate.prototype.getter(name)

新增一个 getter 到 proto 对象,访问该 getter 即可访问 proto 的 prop 的对应 getter。

Delegate.prototype.setter(name)

同 getter。

Delegate.prototype.access(name)

在 proto 上同时新增一个 getter 和一个 setter,指向 proto.prop 的对应属性。

Delegate.prototype.fluent(name)

access 的特殊形式。

实例:

const delegate = require('delegates')

const request = {
  get acceptJSON(){
    return '123'
  }
}

let proto = {
  get title(){
    return 'my title is delegates'
  }
};


proto.request = Object.create(request)

delegate(proto, 'request')
  .getter('acceptJSON')

console.log(proto.acceptJSON)

说明:在绑定delegate之前,如果被代理的对象不是root对象的内部属性,需要将其设置为root对象的内部属性。

基于源码说明:这里只举例getter

Delegator.prototype.getter = function(name){
  var proto = this.proto;
  var target = this.target;
  this.getters.push(name);

  // 使用 __defineGetter__ 绑定 name getter 到 proto
  proto.__defineGetter__(name, function(){
    // 注意 this 指向 proto 本身,所以 proto[name] 最终访问的还是 proto[target][name]
    return this[target][name];
  });

  // 此处 this 指向 delegator 实例,构造链式调用
  return this;
};

1,源码使用了__defineGetter__,即将被废弃,请使用Object.defineProperty()代替

2,this[target][name]指出在代理内部对象后,访问root对象上的属性,root会先获取到被代理的内部属性,再取到内部属性上的属性。

koa中delegate的应用

主要核心 application的createContext方法,会在listen时执行该方法

  createContext(req, res) {
    const context = Object.create(this.context);
    const request = context.request = Object.create(this.request);
    const response = context.response = Object.create(this.response);
    context.app = request.app = response.app = this;
    context.req = request.req = response.req = req;
    context.res = request.res = response.res = res;
    request.ctx = response.ctx = context;
    request.response = response;
    response.request = request;
    context.originalUrl = request.originalUrl = req.url;
    context.state = {};
    return context;
  }

上面代码将request, response赋值给了context实例,所以之后可以使用delegate

参考:https://www.cnblogs.com/DM428/p/11069522.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值