[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