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