-1

When I define a custom element like this:

customElements.define(
   "my-tag",
   class extends HTMLElement {
      constructor() {
         var data = {};
         ...

When I use the element multiple times, like:

<div>
   <my-tag yadda="yadda"></my-tag>
   <my-tag yadda="yadda2"></my-tag>
</div>

I notice that 'data' is shared among all the instances of 'my-tag'.

I also tried creating as a property, like:

customElements.define(
   "my-tag",
   class extends HTMLElement {
      constructor() {
         this.data = {};
         ...

But still got the same shared memory across the instances.

What am I missing?

vuco
  • 161
  • 2
  • 6
  • 1
    Post is Unclear what your problem is. Since `my-tag` has a property `data` defined in it's constructor, All instances of my-tag will contain a data property as defined which contains a value Local to that instance. – Ethan Snow Jun 07 '21 at 02:37
  • Please may you confirm that each instance actually shares the same value? As @EthanSnow has said. – evolutionxbox Jun 07 '21 at 09:35
  • Post a working (or in your case failing) example; use the [ < > ] button in the SO editor to add code. Because the **incomplete** code you show should not exhibit the behavior you describe... the one thing I can think of.. are you using ``document.querySelector("my-tag")`` and thus always get the **first** tag? – Danny '365CSI' Engelman Jun 07 '21 at 10:52
  • I finally managed to detect a portion of my code where the local variable data was being superseded from its value from the other instances. So, I mistakenly thought that in some misterious way the variable wasn't local but global. So, I must apologize for all the inconvenience I caused asking this question! Sorry for my mistake! – vuco Jun 07 '21 at 17:04

1 Answers1

2

Every Custom Element has its own scope:

<my-tag id="ONE"></my-tag>
<my-tag id="TWO"></my-tag>

<script>
  customElements.define(
    "my-tag",
    class extends HTMLElement {
      constructor() {
        super() // sets AND returns this scope
              .data = Math.random(); // chain on super, just because we can
        console.log("constructor", this);
      }
      connectedCallback() {
        console.log("connected" , this.id, this.data, this);
      }
      
    })
</script>
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49