为什么我得到TypeError X不是一个函数

问题描述 投票:0回答:1

我有一个功能对象。当我调用该函数时,它抛出的是TypeError而不是函数。但是该功能看起来正确。

抛出类型错误的函数是showSection。它由showAddCreatureSection调用。 hideSection,hideAddCreatureSection,hideEncounterLog函数都正常工作。

我不知道为什么hideSection抛出typeError并寻找原因

JavaScript的

let informationArea = {
    informationArea: document.getElementById('tracker_additional_area'),
    addCreatureSection: document.getElementById('addCreatures'),
    encounterLogSection: document.getElementById('log'),

    hideSection: function(section_to_be_hidden){
        section_to_be_hidden.classList.add('hide');
    },

    showSection: function(section_to_be_shown){
        console.log('showSection');
        section_to_be_shown.classList.remove('hide');
    },

    hideAddCreatureSection: function(){
        this.hideSection(this.addCreatureSection);

        if(is_encounter_running === false || is_encounter_started === false){
            trackerButtons.add_creature_button.classList.remove('hide');
        }
    },

    showAddCreatureSection: function(){
        console.log('showAddCreatureSection');
        this.showSection(this.addCreatureSection);
    },

    hideEncounterLog: function(){
        this.hideSection(this.encounterLogSection);
    },

    showEncounterLog: function(){
        this.showSectionInInformationArea(this.encounterLogSection);
    },

    closeSection: function(exit_section_button){
        switch(exit_section_button.getAttribute('id')){
            case 'addCreatures':
                this.hideAddCreatureSection();
                break;
            case 'encounterLog':
                this.hideEncounterLog();
                break;
        }
    }
};
trackerButtons.add_creature_button.addEventListener('click',informationArea.showAddCreatureSection);
javascript object typeerror
1个回答
2
投票

这里的问题是注册addEventListner()函数会导致this引用window对象而不是您期望的上下文。

如果可以使用ES6箭头功能,您可能希望将代码更改为:

trackerButtons.add_creature_button.addEventListener('click', () => { informationArea.showAddCreatureSection });

如果没有,请使用:

trackerButtons.add_creature_button.addEventListener('click', function () { informationArea.showAddCreatureSection }.bind(this));
© www.soinside.com 2019 - 2024. All rights reserved.