0

I have a Javascript class inside my global.js like this:

class CustomModal extends ModalDialog {
    constructor() {
        super();
        this.modals = [{
                name: 'quick-select',
                title: 'Quick Select',
            },
            {
                name: 'main-menu',
                title: 'Menu',
            },
            {
                name: 'notify-me',
                title: 'Notify When Back in Stock',
            },
        ];
    }
}

window.CustomModal = CustomModal;

Now I want to access the class properties from outside the class inside an inline script tag, like this:

<script>
    document.addEventListener('DOMContentLoaded', function() {
        console.log('window.CustomModal.modals', window.CustomModal.modals)
    });
</script>

but I'm getting undefined. What am I doing wrong? I want to access properties and functions. I also want to change variables. My main goal is to add another modal to the array, like this:

<script>
    document.addEventListener('DOMContentLoaded', function() {
        window.CustomModal.modals.push({ name: 'new-modal', title: 'New Modal' });
    });
</script>

Thanks in advance!

Phillip
  • 121
  • 7

1 Answers1

0

You defined a class, hence you should instantiate it:

window.CustomModal = new CustomModal();

In your attempt, you only set a reference of the prototype of that class.

Mario Vernari
  • 6,649
  • 1
  • 32
  • 44
  • Thank you. Should I add this inside the global.js? Because I'm getting "Illegal constructor" – Phillip Jan 16 '23 at 10:22
  • I'm afraid that there's more behind, then. I don't see reasons for such error. Could you disclose more code, that is about the `CustomModal` window's field? – Mario Vernari Jan 16 '23 at 10:30
  • The error gets called at "new ModalDialog" and "new CustomModal" at the line `super()` inside the constructor. `class ModalDialog extends HTMLElement { constructor() { super(); ...` and `class CustomModal extends ModalDialog { constructor() { super(); ...` after I added this line inside my global.js `window.CustomModal = new CustomModal();`. I also define CustomModal as a custom element, if that's relevant. Like this: `if (!customElements.get('custom-modal')) customElements.define('custom-modal', CustomModal);` – Phillip Jan 16 '23 at 10:39
  • I believe you should read the answer to this post. It looks the same problem you have: https://stackoverflow.com/questions/41521812/illegal-constructor-with-ecmascript-6 – Mario Vernari Jan 16 '23 at 10:48