在初始化对象(特别是对象)时调用一个方法



我正在为对象制作一个迷你状态管理器库(因为.不要问.(,我想使用这样的方法(伪代码(

states = {}
when object is initialized {
if object.keys.states {
states[object.name] = object.keys.states;
}
}
/*
When object is initialized:
if object.keys.states exists:
states[object.name] = object.keys.states
*/

有没有一种方法可以在typescript/javascript 中实现这一点

这是打字脚本吗?如果这是typescript,您可以使用一个类和一个接口来执行该代码,或者使用类中的构造函数

class states {
states: State[] = [];
constructor(statesc?: State[])
{
if (statesc) {
for(var state in statesc)
{
//no need to do objects keys if you can rotate trough the given parameter
//btw only a class constructor can be called when an object is instantiated otherwise you need to do the 
//logic after it has been created
this.states.push(statesc[state]);
}
}
}

}
interface State{
id: number;
name: string;
}
//then you can do this
let states = new States(states); and the constructor gets called

最新更新