Skip to content

Instantly share code, notes, and snippets.

@ada-lovecraft
Last active August 29, 2015 14:27
Show Gist options
  • Save ada-lovecraft/216eb7cc156ac9914d69 to your computer and use it in GitHub Desktop.
Save ada-lovecraft/216eb7cc156ac9914d69 to your computer and use it in GitHub Desktop.
ES6 Classes with public and private properties
// private variables
let baz = 'baz';
export default class Foo {
constructor() {
// public
this.bar = 'bar';
}
//public methods
log() {
console.log('bar:', this.bar, ':: baz:', baz);
}
zap() {
baz = 'zab';
}
get baz() {
return baz;
}
set baz(nv) {
throw new Error('baz is private... you may not set it');
}
}
import Foo from './Foo';
var foo = new Foo();
foo.log();
// -> bar: 'bar' :: baz: 'baz'
console.log(foo.bar);
// -> 'bar';
console.log(foo.baz);
// -> 'baz'
foo.bar = 'rab';
foo.zap();
foo.log();
// -> bar: 'rab' :: baz: 'zab'
foo.baz = 'zap';
// -> ERROR: baz is private.. you may not set it
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment