我们如何在nodeJS中使用module.exports返回函数
How do we return function using module.exports in nodeJS?
我们如何在nodeJS中使用module.exports返回函数?
file_1书.js
module.exports = function() {
var points = 0;
return {
rate: function(value) {
points = value;
},
get: function() {
return points;
}
}
}
书.js是根文件。我们创建了两个不同的实例,但无法将 root 的方法获取到脚本.js文件。
file_2主要.js
var bA = require('./book.js');
var bB = require('./book.js');
bB.rate(10);
bB.get();
输出 => can not find rate and get method.
由于该函数返回一个引用rate
和get
函数的对象,因此您需要使用 ()
on require 来执行它,如下所示:
var book = require('./book.js')();
book.rate(10);
book.get();
你返回一个返回对象的函数。
调用函数并获取对象
/*file_2 main.js*/
var bA = require('./book.js')();
var bB = require('./book.js')();
bB.rate(10);
bB.get();
以防
万一有人遇到与我相同的问题我的代码有问题。最近意识到我正在进行一些 API 调用,因此在从 API 端点获取值之前返回了一个对象
我在函数调用前面添加了异步,它奏效了!
var util=require('./app/Utils')
const url=await util.getInfo();
您还可以为匿名导出函数提供一个名称,如下所示
module.exports.myfun = function() {
var points = 0;
return {
rate: function(value) {
points = value;
},
get: function() {
return points;
}
} }
然后在另一个文件中使用该函数作为
var inc = require('./comp.js');
var mod = inc.myfun();
mod.rate(10);
console.log(mod.get());
这样,您就不需要在需要时使用"()",尽管也可以使用该选项
相关文章:
- 为什么要对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
- 节点module.exports返回undefined