DEV Community

Slick3gz
Slick3gz

Posted on

 

JS Data Privacy

Hello again 👋

I’ve been grinding in the lab trying get a deeper understanding of Javascript. I’m currently working on a tiny project utilizing some ES6 features. I noticed while creating some classes that instance variables don’t seem to have much protection from outside interference. I would like to hear from other devs on how they go about protecting their instance data in production or if that’s even a valid issue?

Top comments (5)

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”.

 
slick3gz_ profile image
Slick3gz

Do you use TypeScript by itself or use it mainly for a framework? I recently picked up a course on Udemy from Stephen Grider that teaches using TypeScript with Angular.

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!