Reflectionesque behavior in JavaScript


 

Here’s a little something in my continued investigation of JavaScript and its many wonders (man, that sounds strange!)…

Okay, so for today’s topic I’ll look at some ‘reflectionesque’ behavior of JavaScript.  As many know, the class Object can be used as an associative array.  For instance:

var myvar = new Object();
myvar[“value1”] = 42;
assert(42, myvar[“value1”]);  //would be true

What many may not know is that objects will behave as associative array whether we like it or not.  Properties (fields or functions) that we add to an object’s prototype will show up in a foreach construct if we iterate over an object.  This means that we could iterate over an object to see what’s supported by its prototype/interface…sort of like reflection in .Net.  This can be helpful if we want to ensure that a property is supported by a given instance.  If it’s not supported we can either inject the property/function at runtime so that the object doesn’t cause any problems or we could bypass behavior that depends on the property.  Also, we could take disparate classes that support the same “interface” and apply polymorphic ideas.  In the example I show an attempt at getting the value of the ‘name’ property from three different classes.

So that joe has something to play with, I’ve attached a script file called reflectionesque.js (zipped) that illustrates some of this.  I’ve also attached a screen shot that shows the output:

How’d he get that image up there?