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

问题描述 投票:0回答:2

这是我的代码,我通过初始化数组或用户然后定义其上的操作来模拟 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
        }

还有更好的办法吗?

class typescript static-methods
2个回答
4
投票

你可以这样做:

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

0
投票

您可以在“静态”块中初始化静态变量。

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

请参阅 MDN 网络文档

© www.soinside.com 2019 - 2024. All rights reserved.