I was wondering if there’s any benefit of using Object method vs Function expression in this particular case or if it’s rather unnecessary.
I made a singleton for this question that is inside of World.js for example.
If you ask me why I’m doing it this way, I’m experimenting with different ways of writing my code and learning different design patterns.
class World {
constructor() {
if ( !World._instance ) {
World._instance = this;
this.allowTravel = false;
}
return World._instance;
}
isTravelAllowed() {
return this.allowTravel;
}
planTrip() {
if ( this.isTravelAllowed() ) {
return "Let's plan a trip";
}
return "Sorry! As of now, It's impossible to plan a trip";
}
// ...
}
export default World;
Whether there is a better way of doing it or not, I would say there’s nothing wrong with this.
Now, let’s say I make a function expression isTravelAllowed()
outside of the class declaration (not exporting it, just using it inside World.js) and update planTrip()
method.
const isTravelAllowed = () => World._instance.allowTravel;
// Get rid of isTravelAllowed() method
// Updating planTraip() method to this instead
planTrip() {
if ( isTravelAllowed() ) {
return "Let's plan a trip";
}
return "Sorry! As of now, It's impossible to plan a trip";
}
The only reason why I did this, is because I thought if ( isTravelAllowed() )
just looked tidier than if ( this.isTravelAllowed() )
. Whether that sounds like the dumbest reason to do something like this or not, it bothered me enough to change it. It looks more readable, I guess.
This hypothetical function expression isTravelAllowed()
will be called within the singleton multiple times.
So is there any reason why I shouldn’t do something like because of consistency issue, going against a certain design pattern, unnecessarily complicating things, or any other reasons you can think of?
I’d love to hear what you think and would love to learn what I can to improve!