为了账号安全,请及时绑定邮箱和手机立即绑定

AOP in JavaScript

标签:
架构

AOP stands for Aspect-oriented programming. I think the main point of this technology is the ability to add code before or after a function execution.

After some digging on the internet, i write my implement of AOP in JavaScript.

1. First, see the original functin:

function hello() {
for (var i = 0; i < arguments.length; i++) {
arguments[i] += "[hello]";
}
return arguments;
}
var args = hello('World', 'JavaScript');
console.log(Array.prototype.join.apply(args, [' ']));
// World[hello] JavaScript[hello]

2. I want to add before aspect function like this:

aspect.before(window, 'hello', function() {
for (var i = 0; i < arguments.length; i++) {
arguments[i] += "[before]";
}
return arguments;
});

Therefore i give the aspect object like this:

var aspect = {
before: function(context, targetName, fn) {
var target = context[targetName];
context[targetName] = function() {
return target.apply(context, fn.apply(context, arguments));
};
}
};

Now,the result is:

// World[before][hello] JavaScript[before][hello]

You can see, the before function has been injected before the original function's execution.

3. Let's finish the example, add another aspect.after function:
var aspect = {before: function(context, targetName, fn) {
var target = context[targetName];
context[targetName] = function() {
return target.apply(context, fn.apply(context, arguments));
};
},
after: function(context, targetName, fn) {
var target = context[targetName];
context[targetName] = function() {
return fn.apply(context, target.apply(context, arguments));
};
}
};
function hello() {
for (var i = 0; i < arguments.length; i++) {
arguments[i] += "[hello]";
}
return arguments;
}
aspect.before(window, 'hello', function() {
for (var i = 0; i < arguments.length; i++) {
arguments[i] += "[before]";
}
return arguments;
});
aspect.after(window, 'hello', function() {
for (var i = 0; i < arguments.length; i++) {
arguments[i] += "[after]";
}
return arguments;
});
var args = hello('World', 'JavaScript');
console.log(Array.prototype.join.apply(args, [' ']));
// World[before][hello][after] JavaScript[before][hello][after]

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消