Skip to content

Instantly share code, notes, and snippets.

@zetavg
Last active May 4, 2019 01:53
Show Gist options
  • Save zetavg/ca649b807854e96f9fd3567ff9f088e4 to your computer and use it in GitHub Desktop.
Save zetavg/ca649b807854e96f9fd3567ff9f088e4 to your computer and use it in GitHub Desktop.
JS private property using function scopes.
const Person = (() => {
const getName = privateProperties => privateProperties.name.split(' ')[0]
const setName = (privateProperties, name) => {
privateProperties.name = name
}
const getAge = privateProperties => privateProperties.age - 4
const setAge = (privateProperties, age) => {
privateProperties.age = age
}
return function (name = "Unnamed", age = 0) {
const privateProperties = {
name,
age,
}
Object.defineProperties(this, {
name: {
get: getName.bind(null, privateProperties),
set: setName.bind(null, privateProperties),
},
age: {
get: getAge.bind(null, privateProperties),
set: setAge.bind(null, privateProperties),
},
})
}
})()
const make = (name = "Unnamed", age = 0) => {
let privateName = name
let privateAge = age
return {
get name() {
return privateName.split(' ')[0]
},
get age() {
return privateAge - 4
},
changeName(newName = "") {
privateName = newName
},
getOld() {
privateAge += 1
},
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment