0%

JS AOP

有时候我们需要在某个 function 执行之前或之后执行某些自定义的操作,但又不想去修改封装好的代码,这时候就可以使用 AOP 这一设计模式。 首先我们需要扩展 Function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Function.prototype.before = function(fn){
var self = this;
return function(){
typeof fn === 'function' && fn.apply(this, arguments);
return self.apply(this, arguments);
};
};
Function.prototype.after = function(fn){
var self = this;
return function(){
var ret = self.apply(this, arguments);
typeof fn === 'function' && fn.apply(this, arguments);
return ret;
}
};

使用时是这样的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
window.addEventListener('DOMContentLoaded', function(){
var appendBefore = function(){
appendText('before');
},
appendAfter = function(){
appendText('after');
},
newAbc = abc
.before(appendBefore)
.after(appendAfter)
.after(appendAfter)
.before(appendBefore);
newAbc(); // before before raw after after
});
var appendText = function(text){
var obj = document.querySelector('body'),
str = document.createTextNode(' '+ text +' ');
obj.appendChild(str);
},
abc = function(){
appendText('raw');
};

view demo