DEV Community

loading...

Discussion on: Singleton in JavaScript

Collapse
avalander profile image
Avalander

What is the advantage of using a class for a singleton versus let's say using an object literal?

const mySingleton = {
    name: 'One',
    getName () {
        return this.name
    }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
tomekbuszewski profile image
Tomek Buszewski Author

This is a design pattern (object literal is also one, more specific to the JS). Difference is for example that literal can be extended.

Collapse
avalander profile image
Avalander

In which way can you extend an object literal that you cannot extend your singleton object?

Thread Thread
tomekbuszewski profile image
Tomek Buszewski Author

Sorry, I meant not extending but inherit. You can inherit from object literals by just creating new object based on your original one, like here. In singleton pattern, once you create the instance, it cannot be inherited in any way, because any ancestors will link to the original one.

Sorry again for confusion, lack of sleep has really got me this time :D

Thread Thread
avalander profile image
Avalander

That's not what I would define as inheriting, you're cloning the object and adding extra properties to the clone. Nothing prevents anyone from cloning your singleton instance either, though, as long as they remember to carry on the prototype.

const clone = Object.assign(
    Object.create(SingletonClass.prototype),
    instanceOne,
    { shoutName() { return this.name.toUpperCase() }}
)

console.log(clone.shoutName())
Enter fullscreen mode Exit fullscreen mode
Thread Thread
tomekbuszewski profile image
Tomek Buszewski Author

You are completely right, but here you are stepping away from the merit of the text, which is singleton design pattern. In JavaScript all (or are there some that aren't?) reference types can be cloned and those cloned modified.