繁体   English   中英

使用module.exports进行NodeJS原型设计

[英]NodeJS prototyping with module.exports

我在module.exports应用程序中创建了一个类,并使用module.exports以及require()语句将其带入我的主服务器脚本中:

// ./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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM