简体   繁体   中英

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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