Due to functional requirements, some judgment code needs to be executed before N methods of js, and M methods need to be executed to process the code. If you directly write the code in a specific method to add processing code, it will make the code difficult to maintain. There were two solutions to this demand.
1. Create an abstract class, unify the entry, and then distribute the class to specific methods. However, you need to make a lot of changes to the source code. In addition, distribution is also a problem, such as different method parameters. So I didn't stick to this solution.
2. Move to the AOP programming of spring. The final result is achievable.
I found some information online, modified and sorted out an util class.
Js Code
/*
Aop Tool
Onedear 2011-06-10
*/
Var AOPUtil = {
/*
ClassName: it is called a scope or a class name.
FnName: method name, string type
BeforeFn: before function
*/
Before: function (className, fnName, beforeFn ){
If (typeof (className) = 'function ')
ClassName = className. prototype;
If (typeof (className [fnName])! = 'Function ')
Return;
If (typeof (beforeFn )! = 'Function ')
Return;
Var target = className [fnName];
ClassName [fnName] = function (){
BeforeFn. apply (this, arguments );
Return target. apply (this, arguments );
}
},
BeforeJudge: function (className, fnName, beforeFn ){
If (typeof (className) = 'function ')
ClassName = className. prototype;
If (typeof (className [fnName])! = 'Function ')
Return;
If (typeof (beforeFn )! = 'Function ')
Return;
Var target = className [fnName];
ClassName [fnName] = function (){
Var result = beforeFn. apply (this, arguments );
If (! Result)
Return;
Return target. apply (this, arguments );
}
},
// Same as above
After: function (className, fnName, afterFn ){
If (typeof (className) = 'function ')
ClassName = className. prototype;
If (typeof (className [fnName])! = 'Function ')
Return;
If (typeof (afterFn )! = 'Function ')
Return;
Var target = className [fnName];
ClassName [fnName] = function (){
Var returnValue = target. apply (this, arguments );
AfterFn. apply (this, arguments );
Return returnValue;
}
}
};
Call sample
Js Code
Function before (){
Alert ("before ");
}
Function after (){
Alert ("after ");
}
I am used to defining the following methods:
1. handle = {
TestHandle: function (){
Alert ("testHandle ");
}
}
The call method is
AOPUtil. before (window. handle, "testHandle", after );
2. function test2 (){
Alert ("test2 ");
}
The call method is as follows:
AOPUtil. before (window, "test2", before );
3. var t = function (){};
T. prototype. test = function (param1, param2 ){
Alert (param1 + "_" + param2 );
}
The call method is as follows:
AOPUtil. before (t, "test", before );
Is there any other method definition in js?