2012-09-05 49 views
7

我有這個nodeJS代碼。Node JS - 在同一個文件中調用另一種方法的方法

module.exports = { 

    foo: function(req, res){ 
    ... 
    this.bar(); // failing 
    bar(); // failing 
    ... 
    }, 

    bar: function(){ 
    ... 
    ... 
    } 
} 

我需要從foo()方法內部調用bar()方法。我試過​​以及bar(),但都沒有說TypeError: Object #<Object> has no method 'bar()'

如何從另一個方法調用一個方法?

+0

'module.exports.foo.call(this);'? – ChaosPandion

+0

@Danil foo是從路由器調用的請求處理程序。 – Veera

+0

有些東西肯定會改變'this'的背景,但問題是誰? – ChaosPandion

回答

4

這樣來做:需要

module.exports = { 

    foo: function(req, res){ 

    bar(); 

    }, 
    bar: bar 
} 

function bar() { 
    ... 
} 

沒有關閉。

+0

如此全局'bar()'呢? –

+0

只有在這個模塊中。 – timidboy

+0

這就是Node.js的工作原理。 – timidboy

1

我想你可以做的是bind在傳遞迴調之前的上下文。

something.registerCallback(module.exports.foo.bind(module.exports)); 
1

試試這個:

module.exports = (function() { 
    function realBar() { 
     console.log('works'); 
    } 
    return { 

     foo: function(){ 
      realBar(); 
     }, 

     bar: realBar 
    }; 
}()); 
0

酒吧打算是內部(私人)foo嗎?

module.exports = { 
    foo: function(req, res){ 
     ... 
     function bar() { 
      ... 
      ... 
     } 
     bar();  
     ... 
    } 
} 
0

請嘗試以下代碼。你可以參照從任何地方各功能(需要進口.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; 
0

接受的反應是錯誤的,你需要使用「this」關鍵字從當前作用域調用杆法:

module.exports = { 
     foo: function(req, res){ 

     this.bar(); 

     }, 
     bar: function() { console.log('bar'); } 
    } 
相關問題