Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript object creation

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.

like image 524
karthik Avatar asked Aug 23 '11 11:08

karthik


People also ask

How do you create a new object in JavaScript?

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() .

What is JavaScript object with example?

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.

What is object creation?

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.


1 Answers

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;
like image 109
Jamiec Avatar answered Sep 23 '22 07:09

Jamiec