简介:

  AOP(面向切面的编程)是为了解决功能的独立性与可维护性而提供的一种编程思想。当多个函数大量重复使用同一个功能时通过分层切分,将功能平衡的划分,从而提高低耦合性。

Javascript如何实现AOP

Javascript如何实现AOP

JS中实现:

index.html

<script type="text/javascript" src="index.js"></script>

index.js

//实现调用前拦截
Function.prototype.before = function(func) {
    var _this = this;
    return function() {
        if (func.apply(this, arguments) === false) { //调用前执行AOP函数
            return false;
        }
        return _this.apply(this, arguments); //执行原始函数
    }
}


//实现调用后拦截
Function.prototype.after = function(func) {
    var _this = this;
    return function() {
        var result = _this.apply(this, arguments); //执行原始函数
        if (result === false) {
            return false;
        }
        func.apply(this, arguments); //调用后执行AOP函数
        return result;
    }
}

//通过AOP实现外部功能
var Hello = function(func) {
    return func.before(function() {
       console.log("before");
    }).after(function() {
       console.log("after");
    });
}

//主功能函数
function test() {
    console.log("test function in Hello function");
}

//替换主函数
test = Hello(test);

//运行
test();

相关文章:

  • 2021-12-12
  • 2021-11-08
  • 2021-12-19
  • 2022-12-23
  • 1970-01-01
  • 2022-12-23
  • 2022-02-03
  • 2021-04-11
猜你喜欢
  • 2022-12-23
  • 2021-07-06
  • 2021-05-22
  • 2022-12-23
  • 2022-12-23
  • 2021-05-25
相关资源
相似解决方案