This is the code I'm starting with to prototype goal
into the Creep
class:
Object.defineProperty(
Creep.prototype,"goal",{
set :function(value){
this.memory.goal= value.id;
},
get :function() {
return Game.getObjectById(this.memory.goal);
},
}
)
Now let's suppose I want Creep.goal
not to contain a single value, but multiple values instead, and let every single sub-properties of Creep.goal
have the foresaid accessors.
(So I can easily store multiple game objects into the creep's memory)
These properties are meant to be added at runtime, so I do not know how many there will be nor their names, thus I can't simply copy-paste this code once for every property I'd like there to be.
How should I proceed in order to define the accessors of all possible properties-to-be of an object ?
----- SOLUTION -----
So I was suggested to use a Proxy
for this. It was a completely new concept to me and I've hit a lot of walls, but I got something to work like I wanted !
// Prototyping goal as a proxy
Object.defineProperty(
Creep.prototype,"goal",{
get :function()
{return new Proxy(this.memory.goal, objectInMemory) }
}
)
// Proxy's Handler (my previous accessors)
const objectInMemory= {
set(goal, property, value){
goal[property] = value.id;
return true;
},
get(goal, property){
return Game.getObjectById(goal[property]);
},
}
Not exactly sure what you're aiming for, but if the properties are truly dynamic and have to be evaluated at runtime there are
Proxy
objects that are supported by Screeps' runtime.What this does is it allows you to programmatically intercept all of the messages for an object, including accessing properties.