在JS中实现AOP,都是把一个函数动态的置入到另一个函数里面
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
AOP操作
<script type="text/javascript">
Function.prototype.before = function(beforefn){
var _self = this;
return function(){
beforefn.apply(this,arguments); // 执行before函数
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); // 执行after函数
return ret;
}
};
var func = function(){
console.log('helloWorld!');
}
func = func.before(function(){
console.log("1")
}).after(function(){
console.log("2")
})
func();
</script>
</body>
</html>
本文介绍了一种在JavaScript中实现面向切面编程(AOP)的方法。通过扩展Function.prototype,可以方便地为函数添加前置和后置操作。示例代码展示了如何使用before和after方法来包裹原有函数。
701

被折叠的 条评论
为什么被折叠?



