【问题标题】:Uncaught type error: "(function call) is not a function"未捕获的类型错误:“(函数调用)不是函数”
【发布时间】:2020-04-21 14:13:09
【问题描述】:

我正在尝试通过方法调用函数,但我收到一条错误消息,指出它“不是函数”。我曾经在我的 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
    };
  }
}

【问题讨论】:

  • 问题是因为this 指的是input 元素。我假设您希望它引用包含您的函数定义的外部范围?
  • @RoryMcCrossan 是正确的

标签: javascript jquery class methods constructor


【解决方案1】:

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

}

【讨论】:

  • 谢谢!这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 2017-12-19
  • 2014-07-14
  • 2022-11-19
  • 2019-06-06
  • 2019-05-24
  • 2021-12-15
相关资源
最近更新 更多