Typescript中私有和受保护的构造函数的用法是什么

时间:2018-07-02 10:34:00

标签: typescript

我注意到在Typescript中,您可以将构造函数定义为具有任何访问修饰符(私有,受保护,公共)。有人可以给出一个有效的示例,说明如何在Typescript中使用私有和受保护的构造函数吗?

例如,这是打字稿中的有效代码:

class A
{
    private constructor()
    {
        console.log("hello");
    }
}

3 个答案:

答案 0 :(得分:6)

这可以用于singleton模式。

一种解决方法是完全不让外部代码创建该类的实例。相反,我们使用静态访问器:

class SingletonExample {

    private constructor() {
        console.log('Instance created');
    }

    private static _instance: SingletonExample | undefined;

    public prop = 'value';

    public static instance() {
        if (this._instance === undefined) {
            // no error, since the code is inside the class
            this._instance = new SingletonExample();
        }
        return this._instance;
    }

}

const singleton = SingletonExample.instance(); // no error, instance is created
console.log(singleton.prop); // value
const oops = new SingletonExample(); // oops, constructor is private

答案 1 :(得分:3)

就像在其他语言中一样,此用法实际上是不允许任何人(除了类本身)实例化该类。例如,这对于仅具有静态方法的类(在Typescript中是一种罕见的用例,因为有更简单的方法可以这样做)可能有用,或者允许简单的单例实现:

class A
{
    private constructor()
    {
        console.log("hello");
    }

    private static _a :A
    static get(): A{
        return A._a || (A._a = new A())
    }
}

或特殊的初始化要求,例如async init:

class A
{
    private constructor()
    {
        console.log("hello");
    }

    private init() :Promise<void>{} 
    static async create(): Promise<A>{
        let a = new A()
        await a.init();
        return a;
    }
}

答案 2 :(得分:1)

构造函数-只能是公共的。

公共或私人修饰符仅在设计时使用。使用public或private的目的是对外部“用户”隐藏私有方法/属性。默认情况下,所有方法/道具都是公开的。因此,当您声明这样的内容时:

  export class MyClass{
    myProperty:string;
    constructor(){
       this.doJob();
    }

    doJob ():void{
       this.formatString(this.myProperty);
    }

    private formatString():string{
      return this.myProperty.toUpper();
    }
  }

在此示例中,所有道具/方法都是公共的,并且只有一个私有。因此,当您在某处使用此类时,您可以编写:

let a = new MyClass();
a.myProperty = "public";
a.doJob();
console.log(a.myProperty)
// PUBLIC <-- it become upper case by private method.

您可以访问其他类中的所有公共道具/方法,但只能在此类内部使用私有方法/道具。

受保护的方法/属性仅对孩子可见,而继承该类的孩子。

希望这会有用。