A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

JavaScript AOP 使用
出处:https://www.cnblogs.com/zengyuanjun/p/7429968.html[size=1em]
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

/**
* @desc 面向aop编程
* @param {Function} originFunc - 源方法
* @param {Function} before - 在源代码执行之前的方法体
* @param {Function} after - 在源代码执行之后的方法体
*/
function constructor(originFunc, before, after) {
  return function() {
    before.apply(this, arguments);
    originFunc.apply(this, arguments);
    after.apply(this, arguments);
  }
}


function calcAdd(a, b) {
  console.log(a+b);
  return a + b;
}

// AOP增强
calcAdd = constructor(calcAdd, function() {
  console.log('add before');
}, function() {
  console.log('add after');
});

// 要求依次执行 add before 5 add after
calcAdd(2, 3);



[size=1em]
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

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

// AOP 工厂模式<br><br>var aopFactory = function(before, after) {

  // 构造方法,在原方法前后增加执行方法
  function constructor(originFun){
    function _class(){
      proxy.before.apply(this, arguments);
      originFun.apply(this, arguments);
      proxy.after.apply(this, arguments);
    }
    return _class;
  }

  // 代理对象,a为被代理方法,b为目标对象
  var proxy = {
    add: function(a, b) {
      var fnName = '';
      if (typeof a === 'function') {
        fnName = a.name;
      } else if (typeof a === 'string') {
        fnName = a;
      } else {
        return;
      }
      // 不传对象的话默认为window
      b = b || window;
      if (typeof b === 'object' && b[fnName]) {
        b[fnName] = constructor(b[fnName]);
      }
    },
    before: function() {

    },
    after: function() {

    }
  };

  if (typeof before === 'function') {
    proxy['before'] = before;
  }
  if (typeof after === 'function') {
    proxy['after'] = after;
  }

  return proxy;
}




var printProxy, checkProxy;
     
// 打印参数
function printArguments(){
  for(var i = 0; i < arguments.length; i++){
    console.info("param" + (i + 1) + " = " + arguments);
  }
}

// 打印和
function printSum() {
  var sum = 0;
  for(var i = 0; i < arguments.length; i++){
    sum += arguments;
  }
  console.log('和', sum);
}

// 传入一个打印参数的AOP前增强
printProxy = aopFactory(printArguments, printSum);

function calcAdd(a, b) {
  return a + b;
}

// 传入需要增强的原方法
printProxy.add(calcAdd);
calcAdd(1, 2);








1 个回复

倒序浏览
有问题欢迎添加小优:DKA-2018
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马