DEV Community

Discussion on: JS Data Privacy

Collapse
 
avalander profile image
Avalander

I don't really use classes with Javascript. You can encapsulate private data with closures though.

const Unicorn = name => {
  let level = 0

  return {
    name() {
      return name
    },
    level() {
      return level
    },
    levelUp() {
      level += 1
      return this
    },
  }
}

const twilight = Unicorn('Twilight Sparkle')

twilight.name()    // 'Twilght Sparkle'
twilight.level()   // 0
twilight.levelUp()
twilight.level()   // 1
Collapse
 
slick3gz_ profile image
Slick3gz

Earlier in Jonas Schmedtmann’s JS course he explained that IIFEs and closures could let you pick what you would like to expose to the public. I also read a post by Eric Elliot discussing classes vs function constructors vs factory functions, in which he advocated for the use of factory functions over the other two options for future flexibility. Just wondering if this is how most devs approach this “problem”.