Search code examples
javascriptclassmemory-managementcustom-element

Do the javascript custom elements constructors share the same memory?


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?


Solution

  • 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>