装饰器模式
Chunbin Lv4

装饰函数

应用场景

增加新功能,在不改变原函数的前提下,修改代码

使用AOP装饰函数

目的:依照职责分成粒度更细的函数,然后通过装饰把它们合到一起,有助于我们编写一个松耦合高复用性的系统

案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Function.prototype.before = function(beforefn){
var _self = this // 保存原函数的引用
return function(){
beforefn.apply(this,arguments) // 执行新函数,并保证this不被劫持,新函数接受的参数也
return _self.apply(this,arguments)
}
}

Function.prototype.after = function(afterFn){
var _self = this // 保存原函数的引用
return function(){
const ret = afterFn.apply(this,arguments) // 执行新函数,并保证this不被劫持,新函数接受的参数也
_self.apply(this,arguments)
return ret
}
}


function A(){
console.log('a')
}

function B(){
console.log('b')
}

const BBeforeA = A.before(B)

const BAfterA = A.after(B)

A()

BBeforeA()

BAfterA()

也可以更改为不污染原型链的例子

数据上报统计

把函数拆分为操作+上报数据

1
2
3
4
5
6
7
8
9
const action = function(){
console.log('打开登陆窗')
}

const log = function(){
conosle.log('上报的标签为' + this.getAttribut('tag'))
}

action = action.after(log) // 打开窗口后上报数据
使用AOP动态改变函数的参数

比如有ajax需要每次都带上token,则可以使用Funtion.berfore来改变params
这个可以和umi-request的实现差不多
umi-request是通过extend

插件式的表单验证

分离校验合提交代码

 评论
评论插件加载失败
正在加载评论插件
由 Hexo 驱动 & 主题 Keep
访客数 访问量