var age = Symbol("age");
var person = {
"name" : "Clark",
[age] : 28
};
console.log(person.age); // undefined
console.log(person[age]); // 28for(var key in person){
console.log(person[key]); // Would only log "Clark"
}
Use cases
No risk of collision
var isOpen = Symbol('isOpen');
var elm = document.getElementById('dropdown');
elm[isOpen] = true;
Built in Symbols
var things = [1, 'apple', 2, 'banana', 3, 'pear'],
thing;for(thing of things){
console.log(thing);
}// Output:
// 1
// apple
// 2
// banana
// 3
// pear
Symbol.iterator
things[Symbol.iterator] = function*(){
for(let i = 0; i < this.length; i++){
if(typeof this[i] === "string") yield this[i];
}
}for(thing of things){
console.log(thing);
}
// Output:
// apple
// banana
// pear
Encapsulation without (ab)using closures
Hiding variables using closures
function Television(){
var hasPower = false;
this.powerButton = function(){
if(hasPower){
console.log("TV switched off");
} else {
console.log("TV switched on");
}
hasPower = !hasPower;
}
}
var tv = new Television();
tv.powerButton(); // TV switched on
Hard to debug
Bad for code reuse
function PlasmaTV(){
//Cannot access hasPower
console.log(this.hasPower); //undefined
}
PlasmaTV.prototype = new Television();