'Call a method when an object (specifically an object) is initialized
I am making a mini state manager library for objects (because. don't ask.) and I want to use an approach like this (pseudo-code)
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
*/
Is there a way to achieve this in typecript/javascript
Solution 1:[1]
is this typescript? if this is typescript you could use a class and an interface to execute that code or a constructor inside a class
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Defcicer |
