I have something like this...
define(['ClassA', 'ClassB', 'ClassC'],
function(ClassA, ClassB, ClassC)
{
return {
build: function(className) {
var obj;
switch(className)
{
case 'ClassA': obj = new ClassA(); break;
case 'ClassB': obj = new ClassB(); break;
case 'ClassC': obj = new ClassC(); break;
}
return obj;
}
}
}
This seems ok but is there a better way to write it? I tried replacing switch to
return new arguments[className](); // doesn't work
The closest I can get to is to use a map:
var classes = {
ClassA: ClassA,
ClassB: ClassB,
ClassC: ClassC
}
return new classes[className]();
Is there a better way?
There's really no problem with your object there.
It's fast, efficient and easy to follow.
The only suggestion I'd have is to create a var to hold the value, or to test more-explicitly if className is a suitable string, and is in fact in your list:
Either:
var construct = classes[className];
if (construct) { return new construct(); }
else { /* handle the case where the class doesn't exist */ }
Or:
return classes[className] && (new classes[className]()) || null;
The second checks for classes[className] and should return a new instance if it exists (JS returns the value on the very right of AND)...
OR it will return null.
Maybe null isn't what you want.
But the point is that you should be prepared to handle somebody passing: "Bob" to your factory, despite the fact that there is no Bob class.
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