Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript NodeJS使用module.exports进行原型设计_Javascript_Node.js_Class - Fatal编程技术网

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

Javascript NodeJS使用module.exports进行原型设计,javascript,node.js,class,Javascript,Node.js,Class,我在我的NodeJS应用程序中创建了一个类,并使用module.exports和require语句将其带到主服务器脚本中: // ./classes/clientCollection.js module.exports = function ClientCollection() { this.clients = []; } // ./server.js var ClientCollection = require('./classes/clientCollection.js'); va

我在我的NodeJS应用程序中创建了一个类,并使用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 (test) {
   this.test = test;

}

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

module.exports = ClientCollection;


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

module.exports = function ClientCollection() {
    this.clients = [];
}
不在函数本身之外定义符号ClientCollection,因此您不能在模块中的其他地方引用它以添加到原型中。因此,您需要在外部定义它,然后将其分配给导出:

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

ClientCollection.prototype.addClient = function() {
    // code here
}

module.exports = ClientCollection;

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

module.exports = function ClientCollection() {
    this.clients = [];
}
不在函数本身之外定义符号ClientCollection,因此您不能在模块中的其他地方引用它以添加到原型中。因此,您需要在外部定义它,然后将其分配给导出:

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

ClientCollection.prototype.addClient = function() {
    // code here
}

module.exports = ClientCollection;
我认为你需要一个构造函数。他有一个构造器,我想你需要一个构造器。他有一个构装师。