JavaScript newbie here, I was going through some js code at work when i came across a helper function for object creation, which went like this
createElement = function(name, data){
if(name == TYPES.TEXT){
return new Text(data);
}
else if(name == TYPES.WORD){
return new Word(data);
}
else if(name == TYPES.PARAGRAPH){
return new Paragraph(data);
}
else if(name == TYPES.TABLE){
return new Table(data);
}
<list goes on and on and on... >
}
while this does get the job done i would like to know if there is a better, cleaner way of writing this.
Creating a JavaScript Object Create a single object, using an object literal. Create a single object, with the keyword new . Define an object constructor, and then create objects of the constructed type. Create an object using Object.create() .
In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc.
When you create an object, you are creating an instance of a class, therefore "instantiating" a class. The new operator requires a single, postfix argument: a call to a constructor. The name of the constructor provides the name of the class to instantiate. The constructor initializes the new object.
You're right, excessive if..then
or switch
logic is a code smell and can almost always be refactored into something more elegant. In this case, a factory based upon a name can be refactored into a dictionary with key as that name and value as the function to return
var dictionary = {};
dictionary[TYPES.TEXT] = Text;
dictionary[TYPES.WORD] = Word;
dictionary[TYPES.PARAGRAPH] = Paragraph;
dictionary[TYPES.TABLE] = Table;
createElement = function(name, data){
return new dictionary[name](data);
}
Live example: http://jsfiddle.net/KkMnd/
EDIT: That line in the createElement
method could/should first check that something is configured for the TYPES.*
passed in. A good way is to check that there is an element in the dictionary before trying to call that method.
return (typeof dictionary[name] == 'function') ? new dictionary[name](data) : some_default_value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With