I've used node/JavaScript for a few years and am now just getting familiar with TypeScript. I'm trying to wrap my head around when to use a class and when to use a module in TypeScript.
In JavaScript, I would often create modules like this:
const name = "batman";
function getName() {
return name;
}
module.exports = {
name
};
In TypeScript this same code can be written as:
const name: string = "batman";
export function getName(): string {
return name;
}
However, in reading online, there are a fair amount of examples of singletons in TypeScript. I could also write this code as a singleton class like this:
export default class Singleton {
private static instance: Singleton;
private name: string = "batman";
private constructor() { }
public static getInstance(): Singleton {
if (!Singleton.instance) {
Singleton.instance = new Singleton();
}
return Singleton.instance;
}
public getName() {
return this.name;
}
}
I'm struggling to see why I would ever create a singleton as the module is less code and arguably simpler. It also only exists as a single instance. Are there benefits that the singleton offers?
Yes, a module is much simpler and in many cases the better choice. However, singletons have two advantages:
class
, should the need for multiple instances arise. (And that's the case actually quite often, if your instance is stateful - unlike the code in your example).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.