-1

I am experimenting with a new pattern,
where each newly created Card element
uses the constructor scope to store (private) variables:

pseudo code:

class CardtsCard extends HTMLElement {
    constructor(){
       let private = 666;
       Object.assign(this,{
          getPrivate : () => console.log(private)
       });
    }
    get private(){
       //can not access scope in constructor
       return 42;
    }
}

So:

 el.getPrivate(); // outputs 666
 el.private;      // outputs 42


I have loads of getters and setters
and sticking data ON my elements with this.whatever=value feels a bit weird.

I can extend it to:

class CardtsCard extends HTMLElement {
    constructor(){
       let private = new Map();
       Object.assign(this,{
          setPrivate : (data,value) => private.set(data,value),
          getPrivate : (data) => private.get(data)
       });
    }
}

Question: I am no JS scope expert, are there drawbacks?

Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49

1 Answers1

2

Whenever you call the constructor in the first example, a closure has to be created which contains these "private" variables. For a few elements that doesn't cause any overhead, but for a lot of elements you might see a performance and memory overhead.

Concerning your second example: Map lookups can't be inlined, property lookups can, so they are way more performant (which you will only notice on many operations).

And what benefit do you have through this setup? A public method getPrivate isn't really private isn't it? If you need private variables, mark them as private in some way, and trust everyone using the code to deal with it appropriately.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Actually sometime there's no performance overhead but a performance gain when using private (closure) variable compared to object variable – Supersharp Feb 26 '19 at 21:18
  • @supersharp I wanna see a testcase where that is true. – Jonas Wilms Feb 26 '19 at 21:20
  • So a scope is a scope? a Map inside (an IIFE) is the same as a Map inside the constructor?? Any pointers to "Map and inline"?? First googling gets me more techy Java stuff (I declined learning that a quarter century ago) – Danny '365CSI' Engelman Feb 26 '19 at 21:20
  • @danny after all a `constructor` is just a function (a special one though). If you look up "Hidden Class V8" you'll find more JS related optimizations. Or just [click here](https://v8.dev/blog/fast-properties) – Jonas Wilms Feb 26 '19 at 21:22
  • Tnx Jonas, This is (my) homework: https://richardartoul.github.io/jekyll/update/2015/04/26/hidden-classes.html – Danny '365CSI' Engelman Feb 26 '19 at 21:25
  • @Jonas Wilms there are many examples on jsperf. Anyway performance will depends much more on the author coding technique, the JS engine and the CPU profile than on the differences between closure and classes. And as you stated in most case that doesn't cause any overhead. – Supersharp Feb 26 '19 at 22:09