If you're wishing to go with a more robust and testable approach, you could use a combination of classes and a factory pattern to issue the object. Check out the following, you'll see that with this setup, including more granular logic and testing down the road would come easier and afford you greater flexibility. You're also abstracting away new-ing up the object yourself behind the .issue
call - which can be beneficial and convenient in some cases.
I also notice that you mention your PHP background, so I'm also showcasing a bit of how an object orientated approach can be taken in ES6.
class AbstractShape {
constructor(type) {
this.type = type;
}
getType() {
console.log(`I am a ${this.type}`);
}
}
class Square extends AbstractShape {
constructor(type) {
super(type);
this.sides = 4;
}
getDescription() {
console.log(`I have ${this.sides} equal sides`);
}
}
class ShapeFactory {
static issue(type) {
switch(type) {
case 'Square': return new Square(type);
break;
case 'Circle': /* same pattern with a Circle class */
break;
}
}
}
let shape = ShapeFactory.issue('Square');
shape.getType(); /* I am a Square */
shape.getDescription(); /* I have 4 equal sides */
JSFiddle Link - demo
Furthermore, if you'd like something a bit more fault tolerant than dealing with redundant strings e.g. 'Square'
- there are some creative ways to leverage enum-like approaches that could refine this even further. I'll save the real estate here and not re-hash the code snippet, but will include a fiddle for you to check out.
JSFiddle Link - enum approach demo