Skip to content

Instantly share code, notes, and snippets.

@bga
Created March 6, 2018 20:17
Show Gist options
  • Save bga/e96adc9b01635ad240799b0b7a2e6bfa to your computer and use it in GitHub Desktop.
Save bga/e96adc9b01635ad240799b0b7a2e6bfa to your computer and use it in GitHub Desktop.
js class with private fields
"use strict"
class Foo {
constructor() {
//# make object with private properties atop { this }
const privateObject = {
__proto__: this,
_a: 1
}
//# and bind every method to { privateObject }
Object.getOwnPropertyNames(Object.getPrototypeOf(this)).forEach((name) => {
if(this[name] instanceof Function) {
this[name] = this[name].bind(privateObject)
}
else {
}
})
}
incA() {
this._a += 1
}
getA() {
return this._a
}
}
const assert = function(expr) {
if(!expr) {
throw new Error("Assert failed")
}
}
if(1) {
var foo = new Foo()
assert(foo._a == undefined)
assert(foo.getA() == 1)
foo.incA()
assert(foo.getA() == 2)
assert(foo._a == undefined)
console.log("test ok")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment