Last active
June 16, 2020 07:38
-
-
Save matmar10/a06d0d305e6c70c7a8b8a77b3d89baa0 to your computer and use it in GitHub Desktop.
Demonstrates private members using closure scope
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
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