为什么我得到TypeError X不是一个函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么我得到TypeError X不是一个函数相关的知识,希望对你有一定的参考价值。
我有一个功能对象。当我调用该函数时,它抛出的是TypeError而不是函数。但是该功能看起来正确。
抛出类型错误的函数是showSection。它由showAddCreatureSection调用。 hideSection,hideAddCreatureSection,hideEncounterLog函数都正常工作。
我不知道为什么hideSection抛出typeError并寻找原因
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:PouchDB.plugin不是一个函数