gpt4 book ai didi

javascript - 在 Node 的对象中使用 'this' ?

转载 作者:太空宇宙 更新时间:2023-11-04 03:08:44 24 4
gpt4 key购买 nike

我正在使用 Electron 创建一个小型桌面应用程序并使用 module.exports 导出。在“服务器”端,这工作得很好。但是,当我在前端使用 module.exports 时,根据 Electron 文档,我收到此错误。

未捕获类型错误:this.showProgressbar 不是函数”

var ViewController = {
getPageCount: function (res) {
this.total = res;
this.showProgressbar(res);
},

showProgressBar: function (num) {
$('.progress-container').addClass('show');
$('.progress-bar').style('width', '0%');
}
};

module.exports = ViewController;

在客户端,这就是我访问该文件的方式。

var view = require(__dirname + '/client/ViewController.js');

ipc.on('page_count', view.getPageCount);

在此实例中我应该如何访问内部方法?

最佳答案

ViewController 既不是“类”也不是实例,它是一个具有两个属性的普通 JavaScript 对象。

如果您希望它像类一样运行,并且能够在创建实例时从方法访问其他属性,那么您应该这样做:

var ViewController = function(ipc){
this.ipc=ipc;
this.ipc.on('page_count', this.getPageCount);
};

ViewController.prototype.getPageCount: function (res) {
this.total = res;
this.showProgressbar(res);
},

ViewController.prototype.showProgressBar: function (num) {
$('.progress-container').addClass('show');
$('.progress-bar').style('width', '0%');
}
module.exports = ViewController;

您仍然需要实例化 ViewController :

var ViewController = require(__dirname + '/client/ViewController.js');

var controller = new ViewController(ipc);

关于javascript - 在 Node 的对象中使用 'this' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31252543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com