TypeScript static classes

后端 未结 12 688
太阳男子
太阳男子 2020-12-04 13:34

I wanted to move to TypeScript from traditional JS because I like the C#-like syntax. My problem is that I can\'t find out how to declare static classes in TypeScript.

12条回答
  •  情话喂你
    2020-12-04 14:12

    I was searching for something similar and came accross something called the Singleton Pattern.

    Reference: Singleton Pattern

    I am working on a BulkLoader class to load different types of files and wanted to use the Singleton pattern for it. This way I can load files from my main application class and retrieve the loaded files easily from other classes.

    Below is a simple example how you can make a score manager for a game with TypeScript and the Singleton pattern.

    class SingletonClass {

    private static _instance:SingletonClass = new SingletonClass();
    
    private _score:number = 0;
    
    constructor() {
        if(SingletonClass._instance){
            throw new Error("Error: Instantiation failed: Use SingletonDemo.getInstance() instead of new.");
        }
        SingletonClass._instance = this;
    }
    
    public static getInstance():SingletonClass
    {
        return SingletonClass._instance;
    }
    
    public setScore(value:number):void
    {
        this._score = value;
    }
    
    public getScore():number
    {
        return this._score;
    }
    
    public addPoints(value:number):void
    {
        this._score += value;
    }
    
    public removePoints(value:number):void
    {
        this._score -= value;
    }   }
    

    Then anywhere in your other classes you would get access to the Singleton by:

    var scoreManager = SingletonClass.getInstance();
    scoreManager.setScore(10); scoreManager.addPoints(1);
    scoreManager.removePoints(2); console.log( scoreManager.getScore() );
    

提交回复
热议问题