[英]Node JS - Calling a method from another method in same file
I have this nodeJS code.我有这个 nodeJS 代码。
module.exports = {
foo: function(req, res){
...
this.bar(); // failing
bar(); // failing
...
},
bar: function(){
...
...
}
}
I need to call the bar()
method from inside the foo()
method.我需要从
foo()
方法内部调用bar()
foo()
方法。 I tried this.bar()
as well as bar()
, but both fail saying TypeError: Object #<Object> has no method 'bar()'
.我尝试了
this.bar()
和bar()
,但都失败了TypeError: Object #<Object> has no method 'bar()'
。
How can I call one method from the other?如何从另一种方法调用一种方法?
You can do it this way:你可以这样做:
module.exports = {
foo: function(req, res){
bar();
},
bar: bar
}
function bar() {
...
}
No closure is needed.不需要关闭。
The accepted response is wrong, you need to call the bar method from the current scope using the "this" keyword:接受的响应是错误的,您需要使用“this”关键字从当前范围调用 bar 方法:
module.exports = {
foo: function(req, res){
this.bar();
},
bar: function() { console.log('bar'); }
}
我认为你可以做的是在传递回调之前绑定上下文。
something.registerCallback(module.exports.foo.bind(module.exports));
Try this:试试这个:
module.exports = (function () {
function realBar() {
console.log('works');
}
return {
foo: function(){
realBar();
},
bar: realBar
};
}());
Try the following code.试试下面的代码。 You can refer each function from anywhere (needs to import .js file)
您可以从任何地方引用每个函数(需要导入 .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;
Is bar intended to be internal (private) to foo? bar 是否旨在成为 foo 的内部(私有)?
module.exports = {
foo: function(req, res){
...
function bar() {
...
...
}
bar();
...
}
}
in Node js + Express, you can use this syntax in the same controller在 Node js + Express 中,你可以在同一个控制器中使用这个语法
//myController.js
exports.funA = () =>{
console.log("Hello from funA!")
//cal funB
funB()
}
let funB = () =>{
console.log("Hello from funB!")
}
make sure to use the let keyword before the function and call it with the () parentheses inside the main function确保在函数前使用let关键字,并在主函数内使用()括号调用它
OUTPUT输出
App listening at http://localhost:3000
Hello from fun A!
Hello from fun B!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.