Last active
May 4, 2019 01:53
-
-
Save zetavg/ca649b807854e96f9fd3567ff9f088e4 to your computer and use it in GitHub Desktop.
JS private property using function scopes.
This file contains hidden or 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 = (() => { | |
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), | |
}, | |
}) | |
} | |
})() |
This file contains hidden or 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 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