Tuesday, April 24, 2012

Javascript's object and associative array duality. A dynamic method invocation feature hiding in plain sight

The duality of Object and associative array in javascript is a neat functionality you can tap anytime

var something = new Object();

something["FirstName"] = "Michael";
something.LastName = "Buen";

something["MiddleName"] = "Ignite";
something.Age = "Forever";

window.alert(something.FirstName);
window.alert(something["LastName"]);

window.alert(something["MiddleName"]);
window.alert(something.Age);

alert("iterate");

for(var x in something) alert(x + ": " + something[x]);
​


With that in mind, dynamic method invocation like this is possible:

window.alert('ok');
window.confirm('ok');

var arr = ["alert", "confirm"];

for(i = 0; i < arr.length; ++i) window[arr[i]]("Nice!");

And since the alert function is available on implied this object, alert can be done in these ways:

this.alert("would work");
this["alert"]("This would work too");
alert("works"); // the usual

There's another language which has these sort of duality, C language. Its arrays are pointers can be accessed in almost the same ways. Though some might argue that this duality is confusing for beginners.

No comments:

Post a Comment