无论是业务代码的编写,还是框架层面,我们都可以把行为依照职责分成粒度更细的函数,随后通过AOP装饰函数把它们合并到一起,这有助于我们编写一个松耦合和高复用的系统。
分离业务代码和数据统计代码,是AOP的经典应用之一。往往在项目开发的结尾阶段,我们需要加上数据统计的代码。
比如点击登录按钮,弹出登录浮层,与此同时要进行数据上报,来统计多少用户点击了这个按钮。
<button tag="login" id="button">登录</button>
<script>
var showLogin = function(){
alert('登录弹窗')
log( this.getAttribute( 'tag' ) );
}
var log = function( tag ){
console.log( '上报标签为:' + tag );
// (new Image).src = 'http:// xxx.com/report?tag=' + tag;
}
document.getElementById( 'button' ).onclick = showLogin;
</script>
在showLogin函数里,既要负责打开登录浮层,又要负责数据上报,这是两个层面的功能,在此处却被耦合在一个函数里。使用AOP分离之后,代码如下:
Function.prototype.after = function(afterFn) {
const _self = this
return function() {
const res = _self.apply(this, arguments)
afterFn.apply(this, arguments)
return res
}
}
var showLogin = function(){
alert('登录弹窗!!')
}
var log = function( ){
console.log( '上报标签为:' + this.getAttribute( 'tag' ) );
}
showLogin = showLogin.after(log)
document.getElementById( 'button' ).onclick = showLogin;