Simple JavaScript Object Reflection API (.NET Style)

28. February 2008

I was thinking about how JavaScript JSON serializers go about serializing objects. But how does the serializer know about each of the objects properties? I figured JavaScript must have some method of object reflection (similar to .NET Reflection) and it does.

Here's a simple Reflection namespace that allows you to more easily reflect through an objects methods and properties:

if (typeof PietschSoft == "undefined") var PietschSoft = {};
if (typeof PietschSoft.Reflection == "undefined") PietschSoft.Reflection = {};

PietschSoft.Reflection.GetProperties = function(obj){
    var props = new Array();

    for (var s in obj)
    {
        if (typeof(obj[s]) != "function") {
            props[props.length] = s;
        }
    }

    return props;
};

PietschSoft.Reflection.GetMethods = function(obj){
    var methods = new Array();

    for (var s in obj)
    {
        if (typeof(obj[s]) == "function") {
            methods[methods.length] = s;
        }
    }

    return methods
};

And, here's some simple code using the above simple reflection api:

/// Define our Person Object
Person = function(){
this.FirstName = "";
this.LastName = "";
};
Person.prototype.TestFunction = function(){return "Test Function";};

// Define our instance of the Person object
var p = new Person();
p.FirstName = "Chris";
p.LastName = "Pietschmann";

/// Loop through the Objects Properties
var props = PietschSoft.Reflection.GetProperties(p);
for (var i in props)
{
    alert(props[i] + " : " + p[props[i]]);
}

/// Loop through the Objects Methods
var methods = PietschSoft.Reflection.GetMethods(p);
for (var i in methods)
{
    alert(methods[i] + " : " + p[methods[i]]);
}

General ,

Comments

2/29/2008 11:33:03 PM #
Here's a link to a better "typeof" operator that returns more meaningful information about different type of objects.

http://www.webreference.com/dhtml/column68/
5/6/2008 4:59:51 AM #
I have a fully fleshed out serializer that has some nice features, including being able to convert a JS object to XML:

http://www.iconico.com/workshop/jsSerializer/
5/14/2008 1:50:04 PM #
Thanks for this clear & concise explanation.  I was trying to peek into a javascript object to see the properties it contained.  This code gave me the answer I was looking for.