我有一个带有功能的物体。当我调用函数时,它抛出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);
答案 0 :(得分:2)
这里的问题是注册$.ajax({
type: "POST",
url: "/Home/PostRequest",
data: JSON.stringify(request),
headers: {
"Authorization": "** what to put here? **"
}
contentType: "application/json",
dataType: "json",
crossDomain: false,
success: function (response) {
successCallback(response);
},
failure: function (response) {
console.log("Failed");
},
error: function (xhr, response, thrownError) {
console.log("Error");
}
});
函数会导致addEventListner()
引用this
对象而不是您期望的上下文。
如果可以使用ES6箭头功能,则可能需要将代码更改为:
window
如果没有,请使用:
trackerButtons.add_creature_button.addEventListener('click', () => { informationArea.showAddCreatureSection });