Javascript 未捕获类型错误:“quot;(函数调用)不是函数;
我试图通过一个方法调用一个函数,但我收到一个错误,指出它“不是函数”。我以前在HTML中有JS代码,但在我将其移动到当前位置(使用类和构造函数)后,该功能停止工作。因此,我认为我遗漏了一些与类/构造函数相关的东西,但我不确定是什么 index.js:Javascript 未捕获类型错误:“quot;(函数调用)不是函数;,javascript,jquery,class,methods,constructor,Javascript,Jquery,Class,Methods,Constructor,我试图通过一个方法调用一个函数,但我收到一个错误,指出它“不是函数”。我以前在HTML中有JS代码,但在我将其移动到当前位置(使用类和构造函数)后,该功能停止工作。因此,我认为我遗漏了一些与类/构造函数相关的东西,但我不确定是什么 index.js: import calendarComponent from "./SiteAssets/scripts/calendar"; let isAdmin; async function initComponents() { isAdmin =
import calendarComponent from "./SiteAssets/scripts/calendar";
let isAdmin;
async function initComponents() {
isAdmin = await isAdminMember();
const { globalData, mmUser } = await globalInitProm(isAdmin);
const calendar = new calendarComponent(globalData, mmUser);
calendar.initRoutes();
document.getElementById('getFile').addEventListener('change', calendar.handleFileSelect, false); // ----- click event ----- //
}
initComponents();
export default class {
constructor(globalData, mmUser) {
this.globalData = globalData;
this.isAdmin = mmUser.IsAdmin;
this.calendar = null;
}
initRoutes() {}
handleFileSelect(evt) {
console.log("handleFileSelect fired"); // works
let files = evt.target.files;
if (files.length > 0) {
this.parseAndUploadFile(files[0]); // "Uncaught TypeError: this.parseAndUploadFile is not a function"
}
}
parseAndUploadFile(file) {
console.log("trying to load excel file");
let reader = new FileReader();
reader.onload = function (e) {
// etc
};
}
}
calendar.js:
import calendarComponent from "./SiteAssets/scripts/calendar";
let isAdmin;
async function initComponents() {
isAdmin = await isAdminMember();
const { globalData, mmUser } = await globalInitProm(isAdmin);
const calendar = new calendarComponent(globalData, mmUser);
calendar.initRoutes();
document.getElementById('getFile').addEventListener('change', calendar.handleFileSelect, false); // ----- click event ----- //
}
initComponents();
export default class {
constructor(globalData, mmUser) {
this.globalData = globalData;
this.isAdmin = mmUser.IsAdmin;
this.calendar = null;
}
initRoutes() {}
handleFileSelect(evt) {
console.log("handleFileSelect fired"); // works
let files = evt.target.files;
if (files.length > 0) {
this.parseAndUploadFile(files[0]); // "Uncaught TypeError: this.parseAndUploadFile is not a function"
}
}
parseAndUploadFile(file) {
console.log("trying to load excel file");
let reader = new FileReader();
reader.onload = function (e) {
// etc
};
}
}
要解决此问题,请使用
bind
或delegate callback
export default class {
constructor(globalData, mmUser) {
this.globalData = globalData;
this.isAdmin = mmUser.IsAdmin;
this.calendar = null;
this.handleFileSelect = this.handleFileSelect.bind(this) // bind this here
}
// rest od the code
}
问题是因为
此
引用了输入
元素。我猜您希望它引用包含函数定义的外部作用域?@Rorymcrossan没错,谢谢!这正是我想要的。