【每日一包0026】delegates

本文详细介绍了koa2源码中的委托机制,通过delegates模块实现对象属性代理,包括方法代理、属性获取代理、属性赋值代理及双向代理等。并通过示例展示了如何将request上的方法直接代理到ctx上,以及如何对属性进行读写操作。

[github地址:https://github.com/ABCDdouyae...]

delegates (koa2源码依赖)
委托机制,用于对象属性代理
Delegate(proto, prop)创建一个代理实例,使用proto对象下的prop对象作为被代理者
method(name) 接受一个方法,进行方法代理

将request上的方法直接代理到ctx上

const delegate = require('delegates');

var ctx = {};

ctx.request = {
  fn: function(i){return i}
};

delegate(ctx, 'request')
    .method('fn');

console.log(ctx.fn(1))
getter(name) 属性的获取被代理
var ctx = {
    request:{
        url: 'localhost:8080'
    }
};

delegate(ctx, 'request')
     .getter('url')


console.log(ctx.url);//localhost:8080
setter(name) 属性的赋值代理
var ctx = {
    request:{}
}

delegate(ctx, 'request')
    .setter('other')

ctx.other = '1';

console.log(ctx.request.other)//1
access(name) 赋值和获取值得双向代理
var ctx = {
    request: {}
}

delegate(ctx, 'request')
   .access('method')

ctx.method = 'POST';
console.log(ctx.request.method);//'POST'

ctx.request.method = 'GET';

console.log(ctx.method);//'GET'
fluent(name) 被代理者中该属性有值就返回该值,没有的话可以通过函数调用设置,返回ctx对象
var ctx = {
    request:{
        a : 1
    }
}

delegate(ctx, 'request')
    .fluent('a')

console.log(ctx.a())//1
console.log(ctx.a(2))//{ request: { a: 2 }, a: [Function] }
console.log(ctx.a())//2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值