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静态块
的内容?是否存在任何问题-我查找了,但没有找到。为什么我需要linereturn User.users代码>?不User.users.push(这个)代码>直接修改用户
?TypeScript中是否有类似Java静态块
的内容?有什么问题吗?我找了,但没找到。