Skip to content

Instantly share code, notes, and snippets.

@SevInf
Created February 24, 2020 14:28
Show Gist options
  • Save SevInf/d4d09553669db72b93324ba4a13f86d3 to your computer and use it in GitHub Desktop.
Save SevInf/d4d09553669db72b93324ba4a13f86d3 to your computer and use it in GitHub Desktop.
Private fields demo
// thing that exists and we already using
class TreasureChest {
contents = ['golden coin', 'cobweb'];
}
const chest = new TreasureChest();
console.log(chest.contents);
// how to do "private fields" before
class TreasureChest {
_contents = ['golden coin', 'cobweb'];
numberOfThings() {
return this._contents.length;
}
}
/// it is not really private
console.log(chest._contents);
// "private" variables leak in case of inheritance
class VeryImportantTreasureChest extends TreasureChest {
_contents = new Map(); // leads to more treasure;
}
const brokenChest = new VeryImportantTreasureChest();
console.log(brokenChest.numberOfThings());
// same propsal also has a notion of private fields
class TreasureChest {
#contents = ['golden coin', 'cobweb'];
numberOfThings() {
return this.#contents.length;
}
}
const chest = new TreasureChest();
console.log(chest.#contents); // SyntaxError
class VeryImportantTreasureChest extends TreasureChest {
#contents = new Map();
}
const chest = new VeryImportantTreasureChest();
console.log(chest.numberOfThings()); // no name clashes
// we still can access private fields of other instances
// of the same class
class TreasureChest {
#contents = ['golden coin', 'cobweb'];
hasSameItems(otherChest) {
if (this.#contents.length !== otherChest.#contents.length) {
return false;
}
return this.#contents.every(item => otherChest.#contents.includes(item));
}
}
const chest1 = new TreasureChest();
const chest2 = new TreasureChest();
console.log(chest1.hasSameItems(chest2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment