JS AOP
发布于
有时候我们需要在某个 function 执行之前或之后执行某些自定义的操作,但又不想去修改封装好的代码,这时候就可以使用 AOP 这一设计模式。 首先我们需要扩展 Function:
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;
}
};
使用时是这样的:
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');
};