javascript 高阶函数 实现 AOP 面向切面编程 Aspect Oriented Programming

 AOP的主要作用是吧一些跟核心业务逻辑模块无关的功能 -日志统计, 安全控制, 异常处理- 抽离出来,

再通过"动态织入"的方式掺入业务逻辑模块中.

 这里通过扩展Function.prototype来实现:

// Aspect Oriented Programming
Function.prototype.before = function(beforefn) {
	// 保存原函数的引用
	var __self = this;
	// 返回包含了原函数和新函数的代理函数
	return function() {
		// 执行新函数 修正this
		beforefn.apply(this, arguments);
		// 执行原函数
		return __self.apply(this, arguments);
	}
}

Function.prototype.after = function(afterfn) {
	var __self = this;
	return function() {
		var ret = __self.apply(this, arguments);
		afterfn.apply(this, arguments);
		return ret;
	}
}

var func = function() {
	console.log(2);
}
func = func.before(function() {
	console.log(1);
}).after(function() {
	console.log(3);
});

func();

  Run:

原文地址:https://www.cnblogs.com/mingzhanghui/p/9407016.html