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

时间:2016-02-12 03:12:50

标签: class typescript static-methods

这是我的代码,我通过初始化数组或用户然后在其上定义操作来模拟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()之前我需要创建users,我不想做类似的事情:

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
        }

有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

你可以这样做:

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;
    }
}