Aspect-oriented programming (AOP) is a bit interesting. You can add new functions without modifying the original code. Some js frameworks implement the AOP function, but sometimes we cannot rely on the framework to write programs (the framework may be bulky). We need to implement some functional modules that are suitable for us. The following is my own js AOP, which implements the before and after functions and is only for throwing bricks.
The following is aspect. js, which is the whole process of Implementing AOP.
(Function (window, undefined ){
Function aspect (type ){
Return function (target, methodName, advice ){
Var exist = target [methodName],
Dispatcher;
If (! Exist | exist.tar get! = Target ){
Dispatcher = target [methodName] = function (){
// Before methods
Var beforeArr = dispatcher. before;
Var args = arguments;
For (var l = beforeArr. length; l --;){
Args = beforeArr [l]. advice. apply (this, args) | args;
}
// Target method
Var rs = dispatcher. method. apply (this, args );
// After methods
Var afterArr = dispatcher. after;
For (var I = 0, ii = afterArr. length; I <ii; I ++ ){
Rs = afterArr [I]. advice. call (this, rs, args) | rs;
}
// Return object
Return rs;
}
Dispatcher. before = [];
Dispatcher. after = [];
If (exist ){
Dispatcher. method = exist;
}
Dispatcher.tar get = target;
}
Var aspectArr = (dispatcher | exist) [type];
Var obj = {
Advice: advice,
_ Index: aspectArr. length,
Remove: function (){
AspectArr. splice (this. _ index, 1 );
}
};
AspectArr. push (obj );
Return obj;
};
}
Window. aspect = {
Before: aspect ("before "),
After: aspect ("after ")
};
Return window. aspect;
}) (Window, undefined );
The following is the test code:
Var as = window. aspect;
Var obj = {
Url :"",
Get: function (key ){
Return this ["key"];
},
Set: function (key, value ){
This ["key"] = value;
}
};
Var h1 = as. before (obj, "set", function (key, value ){
// Return an array to modify parameters
Value + = "before-1 ";
// Console. log (value );
Return [key, value];
});
Var h2 = as. before (obj, "set", function (key, value ){
// If there is no return value, the parameter will not change
Value + = "before-2 ";
// Console. log (value );
});
Obj. set ("url", "http://mojijs.com ");
Console. log (obj. get ("url "));
Var h3 = as. after (obj, "get", function (value ){
// If there is no return value, the original function's return value will not be modified.
Value + = "after-1 ";
// Console. log (value );
});
Var h4 = as. after (obj, "get", function (value ){
// If a return value exists, the original function's return value will be modified.
Value + = "after-2 ";
// Console. log (value );
Return value;
});
Console. log (obj. get ("url "));
H1.remove (); // Method for deleting a plane surface
H4.remove (); // Method for deleting a plane surface
Obj. set ("url", "http://baidu.com ");
Console. log (obj. get ("url "));