用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