Skip to content

Instantly share code, notes, and snippets.

@littledan
Created January 26, 2021 18:15
Embed
What would you like to do?
Example adding a private field to an existing object
class Super {
constructor(obj) {
return obj;
}
}
class Adder extends Super {
#field;
constructor(obj) { super(obj); }
static set(obj, val) { obj.#field = val; }
static get(obj) { return obj.#field; }
}
let x = {};
Adder.get(x); // TypeError
Adder.set(x, 1); // TypeError
new Adder(x);
Adder.get(x); // undefined
Adder.set(x, 1); // undefined
Adder.get(x); // 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment