简体   繁体   English

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

[英]NodeJS prototyping with module.exports

I've made a class in my NodeJS app and used module.exports along with a require() statement to bring it into my main server script: 我在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();

Now I'd like to add functions onto my class like so: 现在,我想像这样将函数添加到类中:

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

However when I do this I get the following error: 但是,当我这样做时,出现以下错误:

ReferenceError: ClientCollection is not defined

How do I properly add functions to a class using prototyping in a NodeJS app? 如何使用NodeJS应用中的原型向类中正确添加函数?

I think that you need. 我认为你需要。

function ClientCollection (test) {
   this.test = test;

}

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

module.exports = ClientCollection;

or 要么

function ClientCollection () {

}

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

module.exports = ClientCollection;

For various reasons, this structure: 由于各种原因,此结构:

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

does not define the symbol ClientCollection outside of the function itself so you can't refer to it elsewhere in the module to add to the prototype. 没有在函数本身之外定义符号ClientCollection ,因此您不能在模块的其他位置引用它来添加到原型中。 So, instead, you need to define it outside and then assign it to exports: 因此,您需要在外部定义它,然后将其分配给导出:

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