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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么我得到TypeError X不是一个函数相关的知识,希望对你有一定的参考价值。

我有一个功能对象。当我调用该函数时,它抛出的是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);
答案

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

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

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

如果没有,请使用:

trackerButtons.add_creature_button.addEventListener('click', function () { informationArea.showAddCreatureSection }.bind(this));

以上是关于为什么我得到TypeError X不是一个函数的主要内容,如果未能解决你的问题,请参考以下文章

TypeError:x 不是 Node.js 中的函数

TypeError:BookList 不是构造函数

TypeError:即使定义了方法,“x”也不是函数

未捕获的TypeError:PouchDB.plugin不是一个函数

TypeError: x(...).subscribe 不是函数

TypeError:AWS.SecretsManager 不是使用 proxyquire 进行单元测试的构造函数