未捕获的类型错误:“(函数调用)不是函数”

时间:2020-04-21 14:13:09

标签: javascript jquery class methods constructor

我正在尝试通过方法调用函数,但是我收到一条错误消息,指出它不是“函数”。我曾经在HTML中包含JS代码,但是在将其移至当前位置(利用了类和构造函数)后,该功能停止了工作。因此,我认为我缺少与类/构造函数有关的东西,但我不确定是什么。

index.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();

calendar.js:

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

1 个答案:

答案 0 :(得分:1)

要解决此问题,请使用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

}