如何“;捕获“;关注在Javascript中使用面向方面编程
How to "catch" concern using Aspect Oriented Programming in Javascript?
AOP建议实现类的登录和验证方面,以满足业务逻辑
本文展示了一个在javascript中实现AOP的"around"/"wrap"方法的示例,以验证对象属性的值
http://know.cujojs.com/tutorials/aop/intro-to-aspect-oriented-programming
我想知道使用AOP方法和javascript实现"catch"
假设我们有一个类Thing
,它有多个方法来更改属性.location
。Thing
的实例已在整个应用程序中创建,并且.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
});
- jquery动画可以通过编程链接吗
- 一点javascript元编程&可链接的设置器
- 如何正确编程jQuery动画与平滑(导航栏)
- 如何在服务、技能、投资组合等方面添加滑动效果
- 以编程方式填充组合框道场 (1.8) 的最佳方法是什么?
- 以编程方式选择文本Mobile Safari
- 我们可以使用任意的编程语言来动态化HTML页面吗
- 我如何编程许多不同的条件和操作
- Web编程,简单但适用于机器人项目
- Typescript在语法方面与es6/es7有多大不同
- Thunderbird,如何以编程方式选择第一个选项卡
- 以编程方式获取无线接入点列表
- 使用Javascript/jQuery以编程方式将当前锚点/哈希/片段附加到任何表单操作url
- 通过javascript以编程方式将文件插入HTML输入
- 如何以非编程方式国际化HTML文本
- 在使用javascript的Ajax方面遇到了困难
- 在简单的iMacros编程方面需要帮助
- 使用骨干进行方面编程
- JavaScript提供了函数式编程方面的哪些子集和类似lisp的特性?
- 如何“;捕获“;关注在Javascript中使用面向方面编程