ES6 & private variables (with Symbol)
by Julien Roche
HTML
<fieldset>
<legend>Accessed with "instance[SYMBOL_NAME]"</legend>
<span id="case1"></span>
</fieldset>
<fieldset>
<legend>Accessed with introspection</legend>
<span id="case2"></span>
</fieldset>
Babel + JSX
const Something = (function() {
const SYMBOL_NAME = Symbol();
return class Something {
constructor() {
this[SYMBOL_NAME] = 'a private value';
this.publicVariable = 'a public variable';
}
getPrivateValue() {
return this[SYMBOL_NAME];
}
}
})();
let instance = new Something();
document.querySelector('#case1').innerHTML = instance.getPrivateValue();
let text = '';
for(let i in instance) {
text += `${i} => ${instance[i]}`;
}
document.querySelector('#case2').innerHTML = text;