Aspect Oriented Programming 面向切面编程
目的:针对业务处理过程中的切面进行提取,面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果
特点: 无侵入!
常用: 埋点
实战:
1 // 比如计算所有函数谁最耗时,注意无侵入
2
3 function test() {
4 alert(2)
5 return 'me'
6 }
7
8 Function.prototype.before = function(fn) {
9 var _self = this;
10 return function() {
11 // this改变了 因为闭包的匿名报数 所以this执行window
12 fn.apply(_self, arguments);
13 return _self.apply(_self, arguments);
14 }
15 }
16 Function.prototype.after = function(fn) {
17 // after 先执行本身this 再执行回调
18 var _self = this;
19 return function() {
20 var result = _self.apply(_self, arguments);
21 fn.apply(_self, arguments);
22 return result
23 }
24 }
25
26 // 形成链式 因为第一个返回的是function 而after是挂载在Function的原型上的
27 test.before(function() {
28 alert(1)
29 }).after(function() {
30 alert(3)
31 })()
具体的耗时计算,看官自己补上吧。这里主要讲思想了