Class 如何一次初始化类静态属性

Class 如何一次初始化类静态属性,class,typescript,static-methods,Class,Typescript,Static Methods,下面是我的代码,我通过初始化数组或用户,然后定义对它的操作来模拟用户对象 import IUser = require("../interfaces/IUser"); export class User implements IUser { private static users: User[] = []; constructor(public name: string) { this.name = name; User.

下面是我的代码,我通过初始化数组或用户,然后定义对它的操作来模拟用户对象

import IUser = require("../interfaces/IUser");

export class User implements IUser {

    private static users: User[] = [];

    constructor(public name: string) {

        this.name = name;        
        User.users.push(this);
    }

    private static init()
    {
       //creating some users           
       new User(/****/);
       new User(/****/);
       ... 
    }

    public static findOne(login: any, next:Function) {
        //finding user in users array
    }

    public static doSomethingelse(login: any, next:Function) {
        //doSomethingelse with users array
    }
}
基本上,在执行
findOne(…)
doSomethingelse()
之前,我需要创建
用户,我不想执行以下操作:

public static findOne(login: any, next:Function) {
            User.init();
            //finding user in users array
        }

        public static doSomethingelse(login: any, next:Function) {
            User.init();
            //doSomethingelse with users array
        }

有更好的方法吗?

您可以这样做:

export class User implements IUser {
    private static users = User.initUsers();

    constructor(public name: string) {

        this.name = name;        
        User.users.push(this);
    }

    private static initUsers()
    {
        User.users = [];
        new User(...);
        return User.users;
    }
}

你可以这样做:

export class User implements IUser {
    private static users = User.initUsers();

    constructor(public name: string) {

        this.name = name;        
        User.users.push(this);
    }

    private static initUsers()
    {
        User.users = [];
        new User(...);
        return User.users;
    }
}

为什么我需要行
返回User.users?不
User.users.push(这个)直接修改
用户
?TypeScript中是否有类似
Java静态块
的内容?是否存在任何问题-我查找了,但没有找到。为什么我需要line
return User.users?不
User.users.push(这个)直接修改
用户
?TypeScript中是否有类似
Java静态块
的内容?有什么问题吗?我找了,但没找到。