Created
February 24, 2020 14:28
-
-
Save SevInf/d4d09553669db72b93324ba4a13f86d3 to your computer and use it in GitHub Desktop.
Private fields demo
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
// thing that exists and we already using | |
class TreasureChest { | |
contents = ['golden coin', 'cobweb']; | |
} | |
const chest = new TreasureChest(); | |
console.log(chest.contents); |
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
// 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()); |
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
// 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 | |
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
// 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