继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

AOP in JavaScript

安卓入门学习视频
关注TA
已关注
手记 267
粉丝 68
获赞 387

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]

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP