re: Emulating "Private" Variables in JavaScript with Closures and Factory Functions VIEW POST

FULL DISCUSSION
 

I wonder what the memory performance is like compared to this:

const privates = new WeakMap()
class Animal {
  constructor(name, job) {
    privates.set(this, { name, job })
    this.aPublicOne = true
  }

  // Real Getters
  get name() {
    return privates.get(this).name
  }
  get job() {
    return privates.get(this).job
  }
  // Real Setters
  set name(name) {
    privates.get(this).name = name
  }
  set job(job) {
    privates.get(this).job = job
  }
}

Liek, I know instantiating closures isn't the same as actually declaring separate different functions. But it also is more expensive than object methods, to my great disdain.
Will this be somewhere in the middle, or actually worse than both?

 

I'm not sure myself, honestly. I'd love to know. When I have the time, I'll try to create a rigorous experiment for this using the DevTools Memory tools.

If I were to make an educated guess, I'd say the difference in memory efficiency would be negligible.

 

How funny is it, though, that this method is still using closures, the 5 functions capturing privates :D

It makes you realize that even though closures are so ubiquitous in JavaScript, not everyone truly understands it.

code of conduct - report abuse