JS 类方法返回undefined

这是一个electron应用中封装的一个类,预期目标是点击托盘图标后会切换窗口显隐,但在绑定点击事件时,类方法会返回 undefined,“this.onClick”为什么是undefined?该如何解决呢?

# timer_tray.js
const electron = require("electron");
const { Tray } = electron;

class TimerTray extends Tray {
  constructor(iconPath, mainWindow) {
    super(iconPath);
    this.mainWindow = mainWindow;
    this.on("click", this.onClick.bind(this));
  }
  onClick(event, bounds) {
    const { x, y } = bounds;
    const { width, height } = this.mainWindow.getBounds();
    if (this.mainWindow.isVisible()) {
      this.mainWindow.hide();
    } else {
      const yPosition = process.platform === "darwin" ? y : y - height;
      this.mainWindow.setBounds({
        x: x - width / 2,
        y: yPosition,
        height,
        width,
      });

      this.mainWindow.show();
    }
  }
}
module.exports = TimerTray;


# index.js
const path = require("path");
const electron = require("electron");
const { app, BrowserWindow, Tray } = electron;
const TimerTray = require("./app/timer_tray");
let mainWindow;
let tray;
app.whenReady().then(() => {
  mainWindow = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
      enableBlinkFeatures: true,
      contextIsolation: false,
    },
    width: 300,
    height: 500,
    frame: false,
    resizable: false,
    show: false,
  });
  mainWindow.loadURL(`file://${__dirname}/src/index.html`);

  const iconName =
    process.platform === "win32" ? "windows-icon.png" : "iconTemplate.png";
  const iconPath = path.join(__dirname, `./src/assets/${iconName}`);
  tray = new TimerTray(iconPath, mainWindow);
});
运行结果及报错内容

(node:34920) UnhandledPromiseRejectionWarning: TypeError: Cannot read properties of undefined (reading 'bind')
at new TimerTray (tasky\app\timer_tray.js:8:33)
at tasky\index.js:25:10

不是this.onClick是undefined
是this.onClick.bind是undefined
onClick是个函数,它下面没有bind方法

this.onClick就行了 。不用绑定this 了吧