2012-08-23 13 views
6

Sto scrivendo un modulo node.js che esporta due funzioni e voglio chiamare una funzione dall'altra ma vedo un errore di riferimento non definito.Node.js: chiamata una funzione esportata da un'altra nello stesso modulo

Esiste uno schema per farlo? Realizzo solo una funzione privata e la avvolgo?

Ecco qualche esempio di codice:

(function() { 
    "use strict"; 

    module.exports = function (params) { 
     return { 
      funcA: function() { 
       console.log('funcA'); 
      }, 
      funcB: function() { 
       funcA(); // ReferenceError: funcA is not defined 
      } 
     } 
    } 
}()); 

risposta

8

mi piace questo modo:

(function() { 
    "use strict"; 

    module.exports = function (params) { 
     var methods = {}; 

     methods.funcA = function() { 
      console.log('funcA'); 
     }; 

     methods.funcB = function() { 
      methods.funcA(); 
     }; 

     return methods; 
    }; 
}()); 
+1

Io uso un 'var _PUBLIC = {};' e 'var _privat = {};' e restituire il '_public', che aggiunge una certa leggibilità. –

+2

Oppure puoi semplicemente usare 'this.funcA()' ... – d11wtq

+0

Cosa fa qui "usa strict", btw? – d11wtq

Problemi correlati