Javascript dynamic nature
1. eval() function
eval(string) is a top level built in function which lets you define and execute code on the fly. A programmer my not known in advance what code should be executed. Depending on values of different variables a particular statement may need to be executed at run time.
var fieldList = new Array('field1','field2','field3','field4','field5');
var tempObj;
for (count=0;count<fieldList.length;count++) {
tempObj= eval("document.myForm." + fieldList[i]);
if (tempObj.value.length==0) {
alert(fieldList[i] + " requires a value"); }
}
}
Also, eval() is used to parse JSON string to javascript object representation too.
var value = eval("(" + jsonText + ")");
2. The javascript object is essentially just an associated array, with fields and methods keyed by name. Javascript doesn' have built in concept of inheritence, every javascript object is really an instance of the same base class, a class that is capable of binding memeber fields and functions to itself (as associated array) at runtime.
myObject.shoeSize ="12" <=> myObject['shoeSize']="12"
myObject.speakShoeSize = function() { ...} <==> function speaksth() {...}
myObject.speakShoeSize=speaksth;
** note that NOT speaksth()
javascript function is a type of built-in object. A descendant of Object and can do everything that a Javascript object can such as having properties or other function object attached to it.
We can achieve polymorphic (dynamic binding) easily, for instance
myObject['methodName'](x, y, z); where methodName is a runtime passed in string