Skip to content

Instantly share code, notes, and snippets.

@littledan
Created January 26, 2021 18:15
Show Gist options
  • Save littledan/266cd39419e2cd828b5d78a937f1194a to your computer and use it in GitHub Desktop.
Save littledan/266cd39419e2cd828b5d78a937f1194a to your computer and use it in GitHub Desktop.
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