NodeJS prototyping with module.exports

NodeJS prototyping with module.exports

本文关键字:exports module with prototyping NodeJS      更新时间:2023-09-26

我在NodeJS应用程序中创建了一个类,并使用module.exportsrequire()语句将其引入主服务器脚本:

// ./classes/clientCollection.js
module.exports = function ClientCollection() {
    this.clients = [];
}
// ./server.js
var ClientCollection = require('./classes/clientCollection.js');
var clientCollection = new ClientCollection();

现在我想把函数添加到我的类中,如下所示:

ClientCollection.prototype.addClient = function() {
    console.log("test");
}

然而,当我这样做时,我会得到以下错误:

ReferenceError: ClientCollection is not defined

如何在NodeJS应用程序中使用原型设计将函数正确添加到类中?

我认为您需要。

function ClientCollection (test) {
   this.test = test;
}
ClientCollection.prototype.addClient = function() {
    console.log(this.test);
}
module.exports = ClientCollection;

function ClientCollection () {
}
ClientCollection.prototype = {
      addClient : function(){
          console.log("test");
      }
}
module.exports = ClientCollection;

由于各种原因,这种结构:

module.exports = function ClientCollection() {
    this.clients = [];
}

没有在函数本身之外定义符号ClientCollection,因此您不能在模块中的其他地方引用它来添加到原型中。因此,您需要在外部定义它,然后将其分配给导出:

function ClientCollection() {
    this.clients = [];
}
ClientCollection.prototype.addClient = function() {
    // code here
}
module.exports = ClientCollection;