In our previous article Using Classes in JavaScript we introduced the concept of creating OOP classes. With these JavaScript classes we can now specialize each of these objects and additionally make larger classes by extending many of the specialized ones. In order to accomplish the creation of the javascript class objects we can simply use the new keyword, but the have to error check each time. It’s certainly more convienent to use a JavaScript factory function that returns a new instance of the object we are needing or error check if not found.
function make(type ) {
return eval(â€new †+ type + “()â€);
}
//To use
var someObj = make(â€Arrayâ€);
Quite simply that is it! The whole operation surrounds the eval keyword in that it correctly evaluates the inner text and objectName as an actual instantiation of an object. In this case an Array object is being returned to someObj, which is equal to var someObj = new Array().
In practice we never really call array’s in this manner since they are a default JavaScript object and the only thing we have to remember is the case sensitivity. The usefulness of this type of factory is when calling custom objects that created. When dealing with dozens of different object libraries it can be easy to misspell or use incorrect case spelling when trying to instantiate classes. The factory then gives use an opportunity to catch these errors and handle them.
function make(type ) {
try {
return eval(â€new †+ type + “()â€);
} catch(e) {
return null;
}
}
If you stop and think on how many times an object is created in programs you write (or will
) then think about all the extra lines of code you need to write without the make function.
try {
var person1 = new Person();
} catch(e) {
var person1 = null;
}
try {
var person2 = new Person();
} catch(e) {
var person2 = null;
}
.
.
.
Using this article about the JavaScript factory and the previous article on JavaScript class we have prepared an example application using both of these. Additionally the application uses a Controller class that is in charge of loading all the JavaScript libraries, produces the JavaScript factory function, and even directs the actions on the page. The application is found at http://www.techraving.com/FactoryPage.html Source code is available for downloading as well.

While this solution manages the problem of accidental globals if ‘new’ is omitted, the use of eval() is frightening.