2016-07-29 54 views
0

AOP建议实现记录和验证类的各个方面以满足业务逻辑。
This article显示了一个在JavaScript中实现AOP的“around”/“wrap”方法以验证对象属性值的示例。
http://know.cujojs.com/tutorials/aop/intro-to-aspect-oriented-programming如何在JavaScript中使用面向方面的编程“捕捉”关注?

我想知道一个“抓”表示使用JavaScript的AOP方法的实施。

假设我们有一个类Thing有多个方法改变属性.locationThing的实例已在应用程序中创建,并且.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的每个实例“失踪”,您的方法是什么?

+0

是的,你可以使用'尝试/ catch'用'wrap'。你试过了吗? – Bergi

+0

WTH你是指“失踪”,它与异常有什么关系?为什么你连续分配给一个全局变量三次? – Bergi

+0

我已编辑示例代码。 – Nik

回答

3

添加一个设置(/吸气),用于验证您的状态:

Object.defineProperty(Thint.prototype, "location", { 
    get: function() { 
     return this._location 
    }, 
    set: function(val) { 
     if (!/^on the/.test(val)) // or val == "went missing" or whatever 
      throw new Error("invalid value for .location"); // or fix it or log it etc 
     this._location = val; 
    }, 
    enumerable: true, 
    configurable: true 
});