Javascript如何实现AOP

简介:

  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();

转载于:https://www.cnblogs.com/BruceWan/p/5845756.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值