Last active
August 29, 2015 14:27
-
-
Save ada-lovecraft/216eb7cc156ac9914d69 to your computer and use it in GitHub Desktop.
ES6 Classes with public and private properties
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
// 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'); | |
} | |
} | |
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
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