节点module.exports返回undefined
Node module.exports returns undefined
我对Node.js和module.exports
有问题。我知道module.exports
是一个返回对象的调用,该对象具有指定的任何属性。
如果我有这样的文件结构:
// formatting.js
function Format(text) {
this.text = text;
}
module.exports = Format;
这个:
// index.js
var formatting = require('./formatting');
有没有一种方法可以初始化Format
对象并像这样使用它?
formatting('foo');
console.log(formatting.text);
每当我尝试这样做时,我都会得到一个错误,上面写着formatting is not a function
。然后我必须这样做:
var x = new formatting('foo');
console.log(x.text);
这看起来很麻烦。
在像keypress
和request
这样的模块中,它们可以直接使用,如下所示:
var keypress = require('keypress');
keypress(std.in);
或
var request = require('request);
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
这是怎么回事?
我建议将new
调用封装在它自己的函数中,然后返回:
function Format(text) {
this.text = text;
}
function formatting(text) {
return new Format(text);
}
module.exports = formatting;
这种方式你应该仍然能够做到:
var format = formatting('foo');
console.log(format.text);
编辑:
就request
而言,您必须记住的一件事是,在JavaScript中,函数仍然是对象。这意味着您仍然可以向它们添加属性和方法。这就是他们在request
中所做的,尽管总的来说,解释这个答案中的每一个细节都有点太复杂了。据我所知,他们向request
函数添加了一堆方法(对象上的函数)。这就是为什么你可以立即调用像request(blah, blah).pipe(blah).on(blah)
这样的方法。根据调用request
函数返回的内容,你可以在它的后面链接一些其他方法。当你使用request时,它不是一个对象,而是一个函数(但从技术上讲,它仍然是一个对象)。要演示函数如何仍然是对象,以及如何向它们添加方法,请查看以下简单的示例代码:
function hey(){
return;
}
hey.sayHello = function(name) {
console.log('Hello ' + name);
}
hey.sayHello('John'); //=> Hello John
这基本上就是他们正在做的,只是要复杂得多,还有更多的事情要做
module.exports = Format;
当您将require('./formatting')
时,这将返回Format
构造函数
另一方面,下面的代码将返回Format
的实例,您可以直接调用上的方法
module.exports = new Format();
试试这个:
模块格式:
function Format() {
this.setter = function(text) {
this.text = text;
}
this.show = function() {
console.log(this.text);
}
}
//this says I want to return empty object of Format type created by Format constructor.
module.exports = new Format();
index.js
var formatting = require('./formatting');
formatting('Welcome');
console.log(formatting.show());
- RequireJS向模块传递配置总是返回undefined
- JSON数组数据返回Undefined
- JavaScript”;.方法“;返回undefined
- jQuery可以't获取data-*属性值,返回undefined
- Javascript/JSON警报返回Undefined
- Javascript:firstChild对象返回undefined
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- 当尝试使用ajax读取文件时,变量返回undefined
- 如何避免JSON.stringify在特殊情况下返回undefined,从而为JSON.parse创建字符串失败
- 使用谷歌地图:一个返回undefined的自定义javascript函数
- Json在nodeJs和AngularJs中返回undefined
- 为什么像 Firefox 和 Chrome 控制台中的 '}{' 这样的结构会返回 'undefined'?
- 使用 HTML 和 JavaScript 从表单访问值时返回 undefined
- 在 CoffeeScript 中,当尝试调用类中的方法 (@_methodName) 时,它会返回 undefined
- 解析承诺'当'返回undefined(Javascript)
- NodeJS:zlib.gunzip(body)错误地返回“undefined”
- window.open在chrome扩展中返回undefined
- javascript中的If/else不会为undefined返回else
- “undefined"返回而不是游戏名称
- 为什么“typeof false || undefined”返回"布尔值”;