如何“;捕获“;关注在Javascript中使用面向方面编程

How to "catch" concern using Aspect Oriented Programming in Javascript?

本文关键字:编程 方面 Javascript 捕获 如何      更新时间:2023-09-26

AOP建议实现类的登录和验证方面,以满足业务逻辑
本文展示了一个在javascript中实现AOP的"around"/"wrap"方法的示例,以验证对象属性的值
http://know.cujojs.com/tutorials/aop/intro-to-aspect-oriented-programming

我想知道使用AOP方法和javascript实现"catch"

假设我们有一个类Thing,它有多个方法来更改属性.locationThing的实例已在整个应用程序中创建,并且.location属性可能已设置为"went missing"而未被检测到。

我现在要注意的一个方面是属性.location.location可以设置为任何值,但不能设置为"went missing"。任何时候,Thing的任何实例都不应该将其.location设置为"went missing"

我想在任何实例将.location设置为"went missing"时触发catch。捕获后,我应该能够跟踪哪个方法和哪个实例触发它,从而允许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实例时,您的方法是什么

添加一个setter(/getter)来验证您的状态:

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
});