NodeJS prototyping with module.exports
NodeJS prototyping with module.exports
我在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 () {
}
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;
相关文章:
- 为什么要对define.md和module.exports进行条件检查,以及条件何时通过
- 在jasmine规范中使用module.exports
- 我们可以在一个js文件中有多个module.exports语句吗
- module.exports一个jQuery插件
- “module.exports.instance”是什么意思
- Module.exports通过Mongoose调用返回undefined
- 我可以在Node中以编程方式更改.js文件的module.exports中的JSON对象吗
- 使用module.exports和ES6导出导入
- 调用module.exports上的函数时发生CommonJS非法调用错误
- 如何从module.exports访问函数
- 为什么在定义导出属性之前调用module.exports时仍然有效
- “var self = module.exports;”是什么意思
- this.prototype 和 module.exports 之間的差異
- 我们如何在nodeJS中使用module.exports返回函数
- 在定义foo之前放置“module.exports = foo”是如何工作的
- module.exports scope and node-mysql
- require():使用 module.exports vs 直接分配给 “this”
- Node.js/MongoDB:如何使用module.exports将本地主机数据库URL传递给服务器.js文件
- NodeJS prototyping with module.exports
- Expressjs JavaScript Fundamentals: exports = module.exports