EDIT: IT DOES NOT WORK
Thanks @loganfsmyth
Based on this Private properties in JavaScript ES6 classes, using Symbol() seems to be the best way because:
- Methods are on prototype
- Clean syntax
- Almost private
But only "almost" since we can use Object.getOwnPropertySymbols() to loop through the properties. Now I have fixed the method a little bit, using closure.
const Person = (function () {
const myKey = {};
const lock = Symbol();
return class {
constructor(name, age) {
const data = { name, age }; // PRIVATE PROPERTIES GO INSIDE DATA
this[lock] = key => key === myKey ? data : null; // Lock check
}
info() {
const data = this[lock](myKey); // Open lock for every method
return `Name: ${data.name}, age: ${data.age}`;
}
}
})()
// Extending
const Student = (function () {
const myKey = {};
const lock = Symbol();
return class extends Person {
constructor(name, age, school) {
super(name, age);
const data = { school }; // PRIVATE PROPERTIES GO INSIDE DATA
this[lock] = key => key === myKey ? data : null; // Lock check
}
info() {
const data = this[lock](myKey); // Open lock for every method
return `${super.info()}, school: ${data.school}`;
}
}
})()
var ryan = new Student('Ryan Vu', 25, 'Seneca College');
var jane = new Student('Jane Vu', 29, 'Queen University');
console.log(ryan.info());
console.log(jane.info());
//Name: Ryan Vu, age: 25, school: Seneca College
//Name: Jane Vu, age: 29, school: Queen University
It does have some bad points such as you have to call the lock function for every methods, but overall if your goal is to have a completely private class, I think this is a good way, and it follows the rule of prototype chain also. I'm posting here because I'm not sure if what I think is correct, I'm not experienced in programming. Please correct me. Thank you.
Edit - Brief explanation: All methods get access to private data through a lock. Although the outside can see the lock, only the methods and the lock itself can see the key.