JavaScriptで変数をカプセル化する方法
以下のような感じでできます。ただ普通にクラスを使った方が分かりやすいと思います。
const hoge = () => {
let count
const getCount = () => {
return count
}
const setCount = (value) => {
count = value
}
return {
getCount,
setCount
}
}
const h1 = hoge()
const h2 = hoge()
h1.setCount(100)
console.log(h1.v) // undefined
console.log(h1.getCount()) // 100
console.log(h2.v) // undefined
console.log(h2.getCount()) //undefined
h1.count = 999
console.log(h1.v) // undefined
console.log(h1.getCount()) // 100
console.log(h2.v) // undefined
console.log(h2.getCount()) //undefined
console.log(h1.count) //999
最近のコメント