How to add private data to an arbitary object without using a WeakMap

Viewed 34

Ok. This isn't really a question but rather an epiphany I had today that I would like to share, because I don't know if anyone realizes it.

Consider the following code:

function Id(obj) {
    return obj;
}

class Meta extends Id {
    #data;

    constructor(obj, data) {
        super(obj);
        this.#data = data;
    }

    getData() {
        try {
            return this.#data;
        } catch (ex) {}
    }

    setData(value) {
        try {
            this.#data = value;
        } catch (ex) {
            new Meta(this, value);
        }
    }

    static get = Function.call.bind(this.prototype.getData);
    static set = Function.call.bind(this.prototype.setData);
}

var obj = Object.freeze({}); // !!!! frozen
console.log(Meta.get(obj)); // undefined
Meta.set(obj, "test");
console.log(Meta.get(obj)); // "test"
console.log(Reflect.ownKeys(obj)); // Array []

As you can see, I added a private variable to an external frozen object that can be accessed only by my code.

Thank you for reading and enjoy!!!!

0 Answers
Related