这是我到目前为止发现的:
-
dotvoid http://www.dotvoid.com/2005/06/aspect-oriented-programming-and-javascript/的实现,干净的语法,很好用,这篇文章很好地介绍了为什么/如何使用给定的代码,支持介绍,但有bug,
- Dojo 似乎有一个很好的内置实现dojox http://api.dojotoolkit.org/jsdoc/1.3/dojox.lang.aspect, here http://lazutkin.com/blog/2008/may/18/aop-aspect-javascript-dojo/关于如何使用它的一个很好的介绍,
- 有一个 jQuery 插件,jquery-aop http://code.google.com/p/jquery-aop/,使用更粗糙的语法,在 javascript 对象中传递对象和方法,
-
AspectJS http://zer0.free.fr/aspectjs/aspectjs.js使用更粗糙的语法(需要将切入点类型作为参数传递给单个方法)
就像我说的,dotvoid 的代码不起作用。
我纠正了一点,得到了一些似乎效果更好的东西:
InvalidAspect = new Error("Missing a valid aspect. Aspect is not a function.");
InvalidObject = new Error("Missing valid object or an array of valid objects.");
InvalidMethod = new Error("Missing valid method to apply aspect on.");
function doBefore(beforeFunc,func){
return function(){
beforeFunc.apply(this,arguments);
return func.apply(this,arguments);
};
}
function doAfter(func, afterFunc){
return function(){
var res = func.apply(this,arguments);
afterFunc.apply(this,arguments);
return res;
};
}
Aspects = function(){};
Aspects.prototype={
_addIntroduction : function(intro, obj){
for (var m in intro.prototype) {
obj.prototype[m] = intro.prototype[m];
}
},
addIntroduction : function(aspect, objs){
var oType = typeof(objs);
if (typeof(aspect) != 'function')
throw(InvalidAspect);
if (oType == 'function'){
this._addIntroduction(aspect, objs);
}
else if (oType == 'object'){
for (var n = 0; n < objs.length; n++){
this._addIntroduction(aspect, objs[n]);
}
}
else{
throw InvalidObject;
}
},
addBefore : function(aspect, obj, funcs){
var fType = typeof(funcs);
if (typeof(aspect) != 'function')
throw(InvalidAspect);
if (fType != 'object')
funcs = Array(funcs);
for (var n = 0; n < funcs.length; n++){
var fName = funcs[n];
var old = obj.prototype[fName];
if (!old)
throw InvalidMethod;
var res = doBefore(aspect,old)
obj.prototype[fName] = res;
}
},
addAfter : function(aspect, obj, funcs) {
if (typeof(aspect) != 'function')
throw InvalidAspect;
if (typeof(funcs) != 'object')
funcs = Array(funcs);
for (var n = 0; n < funcs.length; n++)
{
var fName = funcs[n];
var old = obj.prototype[fName];
if (!old)
throw InvalidMethod;
var res = doAfter(old,aspect);
obj.prototype[fName] = res;
}
},
addAround : function(aspect, obj, funcs){
if (typeof(aspect) != 'function')
throw InvalidAspect;
if (typeof(funcs) != 'object')
funcs = Array(funcs);
for (var n = 0; n < funcs.length; n++)
{
var fName = funcs[n];
var old = obj.prototype[fName];
if (!old)
throw InvalidMethod;
var res = aspect(old);
obj.prototype[fName] = res;
}
return true;
}
}