js简易反射类

来源:互联网 发布:写游记的软件 编辑:程序博客网 时间:2024/04/29 12:33
 

<script type="text/javascript">
//反射类
function Reflector()
{
    Reflector.getType=function(obj)
    {
        if (obj == null) {
            return null;
        } else if (obj instanceof Object) {
            return obj.constructor;
        } else if (obj.tagName != null) {
            return obj.tagName;
        } else {
            return typeof(obj);
        }
    }
    Reflector.getAttributes=function(obj)
    {
        var methods = new Array();
        for (key in obj) {
            methods.push(new Type(obj[key], this.getType(obj[key]), key));
        }
        return methods;
    }
    Reflector.getAttributeNames=function(obj)
    {
        var methods = new Array();
        for (key in obj) {
            methods.push(key);
        }
        return methods;
    }
}
function Type(entity, type, name)
{
    this.Entity = entity;
    this.Type = type;
    this.Name = name;
}


//使用示例
var oRef = new Reflector();
var arrRef = Reflector.getAttributes(obj);
var str = '';
for(var i=0;i<arrRef.length;i++)
{
    str += arrRef[i].Type+" : "+arrRef[i].Name+"/n";
}
alert(str);
</script>