【问题标题】:Using 'this' in an object in Node?在 Node 的对象中使用“this”?
【发布时间】:2015-09-23 23:52:57
【问题描述】:

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

Uncaught TypeError: this.showProgressbar is not a function"

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

在这种情况下我应该如何访问内部方法?

【问题讨论】:

  • this.showProgressBar 正在查找 getPageCount 上的 showProgressbar,而不是在 ViewController 对象中。
  • 如果你用这个呢? ipc.on('page_count', view.getPageCount.bind(view))
  • 你也需要用正确的大小写来调用你的函数:this.showProgressBar(res);

标签: javascript node.js electron


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    这是因为在调用回调时,它是在错误的上下文中调用的。要绑定上下文,请使用Function.bind

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

    【讨论】:

      猜你喜欢
      • 2011-07-25
      • 2023-03-03
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 2017-07-26
      • 2013-03-08
      • 1970-01-01
      • 2023-03-22
      相关资源
      最近更新 更多