Creating a JavaScript Object

JavaScript newbie here, I was going through some js code at work when I came across a helper function to create an object that 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 its job, I would like to know if there is a better, cleaner way to write this.

+7
source share
2 answers

You are right, excessive logic if..then or switch is the smell of code and can almost always be reorganized into something more elegant. In this case, a factory based on a name can be reorganized into a dictionary with a key like this name and value as a function for 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); } 

Real-time example: http://jsfiddle.net/KkMnd/

EDIT: This line in the createElement method may / should first verify that something is configured for the passed TYPES.* . A good way is to check for an element in an element before trying to call this method.

 return (typeof dictionary[name] == 'function') ? new dictionary[name](data) : some_default_value; 
+9
source

It would be a little cleaner, but semantically it would be the same to use the switch statement.

 function createElement(name,data){ switch(name) { case TYPES.TEXT: return new Text(data) break; case TYPES.WORD: return new WORD(data) break; default: // etc. code to be executed if no values match } } 
0
source

All Articles