如何初始化class static 属性一次
How to initialize class static property once
这是我的代码,我通过初始化数组或用户然后在其上定义操作来模拟用户对象。
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
}
有没有更好的方法?
你可以这样做:
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;
}
}
这是我的代码,我通过初始化数组或用户然后在其上定义操作来模拟用户对象。
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
}
有没有更好的方法?
你可以这样做:
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;
}
}