TypeScript:如何在没有构造函数的类中内部调用静态函数?

fullStack克里斯

我有一个类,我们称其为CoolClass我正在使用的所有代码来访问它的静态属性。但是,我有一个设置步骤,在CoolClass步骤中,我将其定义为类的一部分。让我们称之为doSetupStuff()为了解决这个问题,我通过设置静态dummy变量来调用它

这是我目前正在运行的解决方案:

export default class CoolClass {
    public static readonly something = 'cool';
    public static readonly somethingelse = 12345;

    // GOAL: how can we call doSomeStuff() only once, without setting this 'dummy' variable?
    public static readonly dummy = CoolClass.doSetupStuff();

    public static doSetupStuff(): void {
        console.log('doing setup...');
        // more logic here...
    }
}

但这对我来说是不正确的,因为我实际上并不需要CoolClass.dummy-我只需要运行其中的内容doSetupStuff()

我知道我可以这样做:

export default class CoolClass {
    public static readonly something = 'cool';
    public static readonly somethingelse = 12345;

    constructor() {
        this.doSetupStuff();
    }

    public doSetupStuff(): void {
        console.log('doing setup...');
        // more logic here...
    }
}

但是我不能静态使用CoolClass。(即,new每次我想在代码的其他部分中使用它时,都必须调用)。

当然,不需要dummy像我当前的解决方案那样设置变量。有人有主意吗?我可以根据需要发布完整的代码,尽管我认为这与我希望实现的模式无关。

TJ人群

我想我可能会声明它,进行设置,然后将其导出

class CoolClass {
    public static readonly something = 'cool';
    public static readonly somethingelse = 12345;

    public static doSetupStuff(): void {
        console.log('yay!');
    }
}
CoolClass.doSetupStuff();
export default CoolClass;

话虽doSetupStuff这么说,但要公开成为可能并非理想之选,除非要由班级的用户调用。如果该函数仅适用于该类的公共方面,则可以隐藏该函数:

class CoolClass {
    public static readonly something = 'cool';
    public static readonly somethingelse = 12345;
}
function doSetupStuff(): void {
    console.log('yay!');
}
doSetupStuff();
export default CoolClass;

就是说,我会被一个单身人士吸引:

class CoolClass {
    public readonly something = 'cool';
    public readonly somethingelse = 12345;

    constructor() {
        console.log('yay!'); // Setup here...
    }
}
export default new CoolClass();

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何直接调用类静态函数

如何在超类的静态函数中获取调用子类的名称?

调用静态函数时如何构造模板化类的静态成员?

如何从php中的类中的静态函数调用非静态方法

静态函数对类构造的好处

没有'new'-不能调用类构造函数-commonjs的Typescript

似乎没有调用静态构造函数?

在类React ES6中调用静态函数

调用继承类中存在的静态函数

如何在超类静态函数中从子类引用静态参数?

C ++如何在命名空间中调用另一个类的静态函数

调用 UIViewController 类的非静态函数

Objective c / 如何将用户实现的静态函数调用到 nsstring 类中?

如何在结构中调用静态无参数构造函数?

如何在带有私有构造函数的类中测试此静态成员?

如何在数组循环中对所有子类进行静态函数调用?

当父类在 C++ 中没有默认构造函数时,如何在继承的类中使用构造函数?

Rust如何在某些结构的静态函数调用中解析类型注释

如何在Symfony2 Twig模板中调用静态函数

如何在仅使用静态函数的类中初始化时捕获错误

如何在Java类上的Kotlin中声明扩展静态函数?

如何在抽象类中存根静态函数 | 打字稿

如何从 javascript 调用静态 Typescript 类函数?

如何在Typescript中的函数内部声明静态变量?

在Java中动态调用静态函数

C ++,在类构造函数中传递非静态函数指针

案例类中的静态函数(Scala)

在静态函数类中返回 this

类中的静态函数和数组