java中attribute用法,用javascript模拟C#的[Attribute]用法

用javascript模拟C#的[Attribute]用法

来源:考试大    [ 2005-11-18 16:10:13 ]    责任编辑:jay

执行结果:

调试信息:

/* 特性(Attributes)是一种崭新的声明性信息。

我们不仅可以通过特性来定义设计层面的信息

(例如help file, URL for documentation)

以及运行时(run-time)信息(例如使XML与class相联系),

而且我们还可以利用特性建立自描述(self-describing)组件。

*/

function Attribute() //Attribute 基类,可以自行定义其中的接口以扩充功能,这里只是一个简单的演示,因此留空

{

}

function TestMethod() //定义一个新的Attribute类 TestMethod,用它来给需要进行单元测试的方法提供额外信息

{

this.name = "TestMethod";

}TestMethod.prototype = new Attribute();

function TestMethodAttribute() //必需的执行方法

{

return new TestMethod();

}

function DebugOutput(bOutput) //定义一个新的Attribute类 DebugOutput,用它来指示是否在测试中输出额外的调试信息

{

this.name = "DebugOutput";

this.isAllowDebugOutput = bOutput;

}DebugOutput.prototype = new Attribute();

function DebugOutputAttribute(bOutput) //必需的执行方法

{

return new DebugOutput(bOutput);

}

Function.__captureAttributes = function(obj)

{

var attributeDef = /\[\w+\].*\n.*(?=\=[\s]*function)/g;

var matches = obj.constructor.toString().match(attributeDef);

if(matches != null)

{

for (var i = 0; i 

{

var part = matches[i].split(/[\s\n]/);

var attrLists = part[0].split(",");

var methodObj = eval(part[part.length-1]);

methodObj.__attributes = new Array();

methodObj.__attributes.__all = new Array();

for (var j = 0; j 

{

if(!/^.+\(.*\)$/.test(attrLists[j].slice(1,-1)))

{

attrLists[j] = "[" + attrLists[j].slice(1,-1) + "()" + "]"; //处理省略括号的情况

}

if(!/^.+Attribute$/.test(attrLists[j].split("(")[0]))

{

attrLists[j] = attrLists[j].split("(")[0] + "Attribute" + "(" + attrLists[j].split("(")[1];

}

var attrObj = eval(eval(attrLists[j])[0]);

methodObj.__attributes.__all.push(attrObj);

methodObj.__attributes[attrLists[j].split("(")[0].replace(/[\[\]]/g,"").replace(/Attribute$/g,"")] = attrObj;

methodObj.__attributes[attrLists[j].split("(")[0].replace(/[\[\]]/g,"")] = attrObj;

}

}

}

}

function UnitTest() //单元测试框架,被赋予[TestMethod]特性的方法会被作为Case执行测试

{

this.errors = 0;

this.passed = 0;

//声明TestMethod特性,testString方法将被runCase方法执行,同时声明了DebugOutput特性,将返回的信息输出到调试窗口

//特性的声明必须放在被指定特性的方法之前,而且要独占一行,如果有多个特性可以以逗号分隔

//包含特性声明的函数要以";"结尾,不可省略

[TestMethod],[DebugOutput(true)]

UnitTest.prototype.testString = function() //测试字符串方法,这里假设自己实现了一个String类然后来测试

{

var testCase = new String();

testCase = "abc";

this.Test(testCase == "abc"); //测试赋值操作

testCase += "def";

this.Test(testCase == "abcdef"); //测试连接操作

this.Test(testCase.length == 6); //测试长度属性

转贴于 考试大 //www.examda.com

27e9a90e5ef2d044aafa2970aa5049e2.gif

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值