Creating a Data Container in Javascript

While working on an interactive novel demo, I happened to need a container for containing flags (aka values that I could check later on to change bits of flavor depending on what a player chose), but I didn’t want to just use a plain ol’ JavaScript object. I wanted to create a true data container where you could set any property you wanted, but you wouldn’t be able to overwrite the data in the container itself.

After experimentation and some searching, I came across Proxies, which let you define custom behavior for basic object methods. With guidance from a Stack Overflow answer, I came up with this:

const Flags = new Proxy ({data: {}}, {
    get: (target, name) => target.data[name],
    set: (target, name, val) => target.data[name] = val
});

That was a fun little bit to figure out, and I got to learn something new. Woohoo!

No Comments

Post a Comment