【问题标题】:Can't call class properties inside inline script tag无法在内联脚本标记内调用类属性
【发布时间】:2023-01-16 17:39:29
【问题描述】:

我的 global.js 中有一个 Javascript 类,如下所示:

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;

现在我想在内联脚本标记内从类外部访问类属性,如下所示:

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

但我得到undefined。我究竟做错了什么? 我想访问属性和函数。我也想改变变量。我的主要目标是向数组添加另一个模式,如下所示:

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

提前致谢!

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你定义了一个class,因此你应该实例化它:

    window.CustomModal = new CustomModal();
    

    在您的尝试中,您只设置了该类原型的引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 1970-01-01
      相关资源
      最近更新 更多