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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值