Is there a way in javascript to create an object from a string?
Here is an example :
configuation object:
var formatter = {
telephone : {
length : 10,
formatClass : "telephoneFormatter"
},
email : {
length : 255,
formatClass : "emailFormatter"
}
}
In the fields creation I could use the following method :
function createFormatter(element){
if(formatter[element].formatClass == "telephoneFormatter"){
var formatObj = new telephoneFormatter()
}
if(formatter[element].formatClass == "emailFormatter"){
var formatObj = new emailFormatter()
}
return formatObj;
}
But I would like to create a the object dynamically, something like
function createFormatter(element){
return new formatter[element].formatClass();
}
The constructors are not available as properties of the window
object, as presented in the solution to "Dynamic Instantiation In JavaScript". The class files are loaded with the page but I cannot find the object developer's tool in chrome. Thus I do not have a handle currently on the classes.
Why do I need to do that ? The application loads form dynamically, and the field are created from an elaborate JSON. While the form is beeing created, the validation is added depending on the structure of the JSON. We never know what validation must be added to a certain field. To complexify the whole thing the validation is different on the locale.
Can that be done?