2016-02-12 70 views
0

這是我的代碼,我通過初始化數組或用戶來模擬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 
     } 

有沒有更好的辦法?

回答

2

你可以做這樣的事情:

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

爲什麼我需要行'返回User.users;'?不是'User.users.push(this);'直接修改'users'? – sreginogemoh