[英]nodejs module with constructor and methods
How can I create a constructor in a nodejs
module? 如何在nodejs
模块中创建构造函数?
The documentation says something like this: 该文档说是这样的:
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
So you can do: var v = square(10);
这样就可以做到: var v = square(10);
I want to acieve something similar, but I have several other methods in my file. 我想要获得类似的东西,但是我的文件中还有其他几种方法。
File: test.js 档案:test.js
exports = module.exports;
// ctor
exports = function(val) {
};
exports.test1 = function(param1) {
return 'a';
};
exports.test2 = function(param1, param2) {
return 'b';
};
How can I add a constructor-like function to my code so I can do this: 如何在代码中添加类似于构造函数的函数,以便执行此操作:
test('val');
var t1 = test.test1('param');
var t2 = test.test1('param');
You were quite close. 你很亲近
The problem is with the first and the second line. 问题出在第一和第二行。 You begin with setting the variable exports to module.exports (and forget to use var), then you override it with the function. 首先将变量export设置为module.exports(并忘记使用var),然后使用函数覆盖它。
So if you want to do that, you need to first set exports.module to the function, and then var exports = module.exports; 因此,如果要执行此操作,则需要首先将exports.module设置为该函数,然后将varexports = module.exports;设置为该函数。
Anyway, I wouldn't suggest that you use this shortcut, since it's confusing and exports is already a global variable in that context. 无论如何,我不建议您使用此快捷方式,因为它令人困惑,并且在这种情况下导出已经是全局变量。
You better use the long syntax and be more clear: 您最好使用长语法,并更加清楚:
module.exports = function(val) {
console.log ('test');
};
module.exports.test1 = function(param1) {
console.log('a');
};
module.exports.test2 = function(param1, param2) {
console.log ('b');
};
Here's a good example: https://github.com/rvagg/through2/blob/master/through2.js 这是一个很好的例子: https : //github.com/rvagg/through2/blob/master/through2.js
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.