节点JS – 在同一个文件中调用另一种方法
我有这个nodeJS代码。
module.exports = { foo: function(req, res){ ... this.bar(); // failing bar(); // failing ... }, bar: function(){ ... ... } }
我需要从foo()
方法中调用bar()
foo()
方法。 我尝试了this.bar()
以及bar()
,但都没有说TypeError: Object #<Object> has no method 'bar()'
。
我怎么能从另一个方法调用一个方法?
这样做:
module.exports = { foo: function(req, res){ bar(); }, bar: bar } function bar() { ... }
不需要closures。
我想你可以做的是在传递callback之前绑定上下文。
something.registerCallback(module.exports.foo.bind(module.exports));
尝试这个:
module.exports = (function () { function realBar() { console.log('works'); } return { foo: function(){ realBar(); }, bar: realBar }; }());
酒吧打算是内部(私人)的富?
module.exports = { foo: function(req, res){ ... function bar() { ... ... } bar(); ... } }
尝试下面的代码。 您可以从任何地方引用每个function(需要导入.js文件)
function foo(req,res){ console.log("you are now in foo"); bar(); } exports.foo = foo; function bar(){ console.log("you are now in bar"); } exports.bar = bar;
接受的响应是错误的,您需要使用“this”关键字从当前范围调用bar方法:
module.exports = { foo: function(req, res){ this.bar(); }, bar: function() { console.log('bar'); } }
- 无法将此文件中的代码缩小
- 是否有可能parsing这个在node.js中的JSON?
- pipe道图像与在请求中发送node.js中的callback主体
- 在javascript中使用asynchronouscallback模式的无限循环
- Socket.IO:如何在同一台服务器上的socket.on()事件之间进行通信/交换数据?
- 在承诺之外返回一个承诺variables
- 如何使用angular postgres和node在configuration文件中显示数据库中的用户信息? 我的代码不起作用
- Rfc2898DeriveBytes在javascript中的等价物?
- node.js:表单HTTP请求模块的身份validation失败