Skip to content

Instantly share code, notes, and snippets.

@matmar10
Last active June 16, 2020 07:38
Show Gist options
  • Save matmar10/a06d0d305e6c70c7a8b8a77b3d89baa0 to your computer and use it in GitHub Desktop.
Save matmar10/a06d0d305e6c70c7a8b8a77b3d89baa0 to your computer and use it in GitHub Desktop.
Demonstrates private members using closure scope
const Person = (function() {
// currentName cannot be modified externaly
let currentName;
function isGoodName() {
return !!currentName.match(/Snehanshu/);
}
class Person {
constructor(name) {
currentName = name;
}
set name(name) {
currentName = name;
}
get name() {
return currentName;
}
get isGoodName() {
return isGoodName();
}
set isGoodName(isGoodName) {
throw new Error('Not allowed');
}
}
return Person;
})();
const a = new Person('Snehanshu Phukon');
console.log(a.name);
console.log(a.isGoodName);
a.isGoodName = false;
const b = new Person('Matthew');
console.log(a.name);
console.log(a.isGoodName);
a.isGoodName = true;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment