AOP建议实现记录和验证类的各个方面以满足业务逻辑。
This article显示了一个在JavaScript中实现AOP的“around”/“wrap”方法以验证对象属性值的示例。
http://know.cujojs.com/tutorials/aop/intro-to-aspect-oriented-programming如何在JavaScript中使用面向方面的编程“捕捉”关注?
我想知道一个“抓”表示使用JavaScript的AOP方法的实施。
假设我们有一个类Thing
有多个方法改变属性.location
。 Thing
的实例已在应用程序中创建,并且.location
属性可能已设置为"went missing"
未检测到。
我想现在要注意的一个方面是属性.location
。 .location
可以设置为任何值,但不能为"went missing"
。在任何时候,Thing
的任何实例都应将其设置为.location
至"went missing"
。
我想触发一个catch
当任何实例将其设置为.location
到"went missing"
。在捕获时,我应该能够跟踪哪个方法和哪个实例触发它,从而允许Thing
相应地处理它的实例。
很像捕捉错误try-catch
,我们可以捕获错误事件并相应地处理它。
function Thing(){
this.location = "in the safe box";
this.move = function(str){
this.location = str;
},
this.walk = function(str){
this.location = str;
},
this.run = function(str){
this.location = str;
}
}
var myBook = new Thing();
var yourBook = new Thing();
var hisBook = new Thing();
var book = [myBook,yourBook,hisBook];
var cycle = 0;
startTimer(function(){
// randomly select which instance and which action
var instance = book[Math.floor(Math.random() * book.length)];
var action = Math.floor(Math.random() * 3);
var location = (Math.random()%5 == 0)? "went missing" : "some where else";
if(action == 1) instance.move(location);
else if(action == 2) instance.walk(location);
else if(action == 3) instance.run(location);
cycle += 1;
},10000);
我们怎样才能抓到一本书.location = "went missing"
?当书籍.location
检测到“失踪”并将其重置为.location
至"in the safe box"
时,我想停止移动操作。我也应该能够跟踪哪本书,通过哪个方法在哪个周期。
找到Thing
的每个实例“失踪”,您的方法是什么?
是的,你可以使用'尝试/ catch'用'wrap'。你试过了吗? – Bergi
WTH你是指“失踪”,它与异常有什么关系?为什么你连续分配给一个全局变量三次? – Bergi
我已编辑示例代码。 – Nik