【问题标题】:NodeJS: Cannot read property 'hide' of undefinedNodeJS:无法读取未定义的属性“隐藏”
【发布时间】:2018-05-15 04:07:16
【问题描述】:

问题

我正在使用 Electron 和 Node,并且遇到了变量 (this.mainWindow) 只能在创建它的函数内部访问的问题。每当事件侦听器触发时,this.mainWindow 是未定义的。这一切都发生在一个类内部,所以this 应该是对该类的工作实例的引用,对吗?

代码

class AppManager {

    constructor (app, options) {
        this.app = app
        this.options = options = {}
        this.bindEvents()
    }

    bindEvents () {
        this.app.on('ready', this.onReady.bind(this))
        this.app.on('window-all-closed', this.onWindowAllClosed.bind(this))
        this.app.on('activate', this.onActivate.bind(this))
    }

    onReady () {
        this.createWindow()
    }

    onWindowAllClosed () {
        if (process.platform !== 'darwin') {
            this.app.quit()
        }
    }

    onActivate () {
        if (this.app.mainWindow === null) {
            this.createWindow()
        }
    }

    onClose (e) {
    // here, this.mainWindow and this.isQuitting are undefined.
        if (this.isQuiting) {
            this.mainWindow = null
        } else {
            e.preventDefault()
            this.mainWindow.hide()
        }
    }

    onClick () {
        // here, this.mainWindow is undefined.
        this.mainWindow.show()
    }

    createWindow () {
    // here, we declare this.isQuitting
        this.isQuitting = false

        this.contextMenu = Menu.buildFromTemplate([
            {
                label: 'Show App',
                click: function () {
                    this.mainWindow.show()
                }
            },
            {
                label: 'Quit',
                click: function () {
                    this.isQuiting = true
                    this.app.quit()
                }
            }
        ])

        this.tray = new Tray('./public/images/icon.ico')
        this.tray.setContextMenu(this.contextMenu)
        this.tray.on('click', this.onClick)

        // at this point, we assign the variable mainWindow to "this".
        this.mainWindow = new BrowserWindow(this.options)
        this.mainWindow.loadURL(url.format({
            pathname: path.join(__dirname, '../../../public/index.html'),
            protocol: 'file:',
            slashes: true
        }))
        this.mainWindow.tray = this.tray
        this.mainWindow.on('close', this.onClose)
    }
}

错误

A JavaScript error occurred in the main process Uncaught exception: TypeError: cannot read property hide of undefined

当我关闭窗口或单击托盘图标时发生错误。那是onCloseonClick 着火的时候,那是this.mainWindowthis.isQuittingundefined 的时候

如果您想了解更多信息,请告诉我。

任何想法或建议表示赞赏:)

【问题讨论】:

    标签: javascript node.js oop scope electron


    【解决方案1】:

    您正在传递this.onClose,但您可能丢失了对this 的引用。

    this.mainWindow.on('close', this.onClose.bind(this));
    

    应该修复它。

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2022-11-29
      • 2023-02-17
      • 2017-06-17
      • 2014-07-28
      相关资源
      最近更新 更多