Skip to content

Instantly share code, notes, and snippets.

@awwright
Last active July 6, 2020 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awwright/68b23fc73ce1c782f31f8a1913c84543 to your computer and use it in GitHub Desktop.
Save awwright/68b23fc73ce1c782f31f8a1913c84543 to your computer and use it in GitHub Desktop.
A pattern for protected class properties in ECMAScript
"use strict";
class A {
#writableSide;
#writableSideInit = false;
constructor(x) {
this.#writableSide = {a: x};
}
initWritableSide() {
if(this.#writableSideInit) throw new Error('writableSide already initialized');
this.#writableSideInit = true;
return this.#writableSide;
}
}
class B extends A {
#writableSide;
constructor(x) {
super(x);
this.#writableSide = this.initWritableSide();
}
log() {
console.log(this.#writableSide);
}
}
new B(1).log();
"use strict";
class A {
#writableSide;
#hasWritableSide;
constructor(x) {
this.#writableSide = this.#hasWritableSide = {a: x};
}
get writableSide() {
const writableSide = this.#hasWritableSide;
this.#hasWritableSide = null;
return writableSide;
}
}
class B extends A {
#writableSide;
constructor(x) {
super(x);
this.#writableSide = this.writableSide;
}
log() {
console.log(this.#writableSide);
}
}
new B(1).log();
"use strict";
class A {
#writableSide;
#hasWritableSide;
receiveWritableSide;
constructor(x) {
this.#writableSide = {a: x};
this.receiveWritableSide(this.#writableSide);
}
}
class B extends A {
#writableSide;
receiveWritableSide(val) {
// for some reason this won't take until the super() call finishes, ahhhhhhh
// "Cannot write private member #writableSide to an object whose class did not declare it"
this.#writableSide = this.writableSide;
}
constructor(x) {
super(x);
}
log() {
console.log(this.#writableSide);
}
}
new B(1).log();
"use strict";
class A {
#writableSide = null;
constructor(x) {
}
makeWritableSide() {
if(this.#writableSide) throw new Error('Cannot re-initialize');
this.#writableSide = {a: x};
return this.#writableSide;
}
}
class B extends A {
#writableSide;
constructor(x) {
super(x);
this.#writableSide = this.makeWritableSide();
}
log() {
console.log(this.#writableSide);
}
}
new B(1).log();
"use strict";
class A {
#writableSide;
constructor(x, passSecrets) {
this.#writableSide = {a: x};
passSecrets(this.#writableSide);
}
}
class B extends A {
#writableSide;
constructor(x) {
let v;
super(x, (_v)=>{ v = _v; });
this.#writableSide = vv;
}
log() {
console.log(this.#writableSide);
}
}
new B(1).log();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment