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]