如何从module.exports
声明中的另一个函数中调用函数?
这是一些简化的代码.
在我的app.js中,我执行以下操作:
var bla = require('./bla.js');
console.log(bla.bar());
Run Code Online (Sandbox Code Playgroud)
而在bla.js里面是
module.exports = {
foo: function (req, res, next) {
return ('foo');
},
bar: function(req, res, next) {
this.foo();
}
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试foo
从函数中访问该函数bar
,我得到:
TypeError: Object # has no method 'foo'
如果我改成this.foo()
只是foo()
我得到:
ReferenceError: foo is not defined
k00*_*00k 310
我想我明白了.我只是改变this.foo()
到module.exports.foo()
,它似乎是工作.
如果某人有更好或更正确的方法,请随时纠正我.
Bre*_*ett 185
您可以在module.exports块之外声明您的函数.
var foo = function (req, res, next) {
return ('foo');
}
var bar = function (req, res, next) {
return foo();
}
Run Code Online (Sandbox Code Playgroud)
然后:
module.exports = {
foo: foo,
bar: bar
}
Run Code Online (Sandbox Code Playgroud)
小智 115
您也可以这样做,使其更简洁和可读.这是我在几个编写良好的开源模块中看到的:
var self = module.exports = {
foo: function (req, res, next) {
return ('foo');
},
bar: function(req, res, next) {
self.foo();
}
}
Run Code Online (Sandbox Code Playgroud)
Vil*_*lle 61
您还可以在(module.)exports.somemodule定义之外保存对模块全局范围的引用:
var _this = this;
exports.somefunction = function() {
console.log('hello');
}
exports.someotherfunction = function() {
_this.somefunction();
}
Run Code Online (Sandbox Code Playgroud)
小智 40
另一个选项,更接近OP的原始样式,是将要导出的对象放入变量并引用该变量以调用对象中的其他方法.然后你可以导出那个变量,你就可以了.
var self = {
foo: function (req, res, next) {
return ('foo');
},
bar: function (req, res, next) {
return self.foo();
}
};
module.exports = self;
Run Code Online (Sandbox Code Playgroud)
dav*_*ler 23
const Service = {
foo: (a, b) => a + b,
bar: (a, b) => Service.foo(a, b) * b
}
module.exports = Service
Run Code Online (Sandbox Code Playgroud)
m.s*_*tos 13
在NodeJs中我遵循这种方法:
class MyClass {
constructor() {}
foo(req, res, next) {
return ('foo');
}
bar(req, res, next) {
this.foo();
}
}
module.exports = new MyClass();
Run Code Online (Sandbox Code Playgroud)
由于Node的模块缓存,这将只实例化一次类:https:
//nodejs.org/api/modules.html#modules_caching
小智 6
为了解决您的问题,我在 bla.js 中做了一些更改并且它正在工作,
var foo= function (req, res, next) {
console.log('inside foo');
return ("foo");
}
var bar= function(req, res, next) {
this.foo();
}
module.exports = {bar,foo};
Run Code Online (Sandbox Code Playgroud)
并且在 app.js 中没有修改
var bla = require('./bla.js');
console.log(bla.bar());
Run Code Online (Sandbox Code Playgroud)