Created
March 6, 2018 20:17
-
-
Save bga/e96adc9b01635ad240799b0b7a2e6bfa to your computer and use it in GitHub Desktop.
js class with private fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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