Javascript NodeJS使用module.exports进行原型设计
我在我的NodeJS应用程序中创建了一个类,并使用module.exports和require语句将其带到主服务器脚本中: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
// ./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;
我认为你需要一个构造函数。他有一个构造器,我想你需要一个构造器。他有一个构装师。