Почему я получаю TypeError X не является функцией - PullRequest
0 голосов
/ 06 декабря 2018

У меня есть объект с функциями.Когда я вызываю функцию, она вызывает ошибку TypeError, а не функцию.Однако функция выглядит корректно.

Функция, выдающая ошибку типа, - это showSection.Это вызывается showAddCreatureSection.Функции hideSection, hideAddCreatureSection, hideEncounterLog все работают.

Понятия не имею, почему hideSection выдает ошибку типа и ищет причину

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);

1 Ответ

0 голосов
/ 06 декабря 2018

Проблема здесь в том, что при регистрации функции addEventListner() this ссылается на объект window вместо ожидаемого контекста.

Если возможно использовать функции стрелок ES6, которые вам могут понадобитьсячтобы изменить свой код на:

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

, если нет, используйте:

trackerButtons.add_creature_button.addEventListener('click', function () { informationArea.showAddCreatureSection }.bind(this));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...