module.exports and inner functions.

128 views
Skip to first unread message

Joseph Arrieta

unread,
Nov 3, 2015, 5:46:40 PM11/3/15
to nodejs
Hi guys,

I have a doubt if I have this a.js:

// a.js
module.exports = {
  someFunction: function() {
    function innerFunction() {
      //code here
    }
    innerFunction();
  }
}

and this other one b.js:

// b.js
function outterFunction() {
//code here
}

module.exports = {
  someFunction: function() {
    innerFunction();
  }
}

NodeJS files are cached whenever we require them, that's so far so good, now my question is does the innerFunction in file a.js its also cached? or everytime I call 
require('a.js').someFunction() the function innerFunction is redefined?

I would like to know about this because in case always the function is redefined I prefer to use the command pattern to define modules in node and then just attach what I just defined to module.exports like this, with this way all the functions will be cached by the mechanism of require (in case the function is always redefined in the file a.js):

// c.js
(function(){
  function outterFunction() {
    // code here
  }

  function someFunction() {
    outterFunction();
  }
})();

module.exports = {
  someFunction: someFunction
}

Thanks in advance guys.

Aria Stewart

unread,
Nov 3, 2015, 10:24:33 PM11/3/15
to nod...@googlegroups.com

> On Nov 3, 2015, at 5:45 PM, Joseph Arrieta <jac.w...@gmail.com> wrote:
>
> Hi guys,
>
> I have a doubt if I have this a.js:
>
> // a.js
> module.exports = {
> someFunction: function() {
> function innerFunction() {
> //code here
> }
> innerFunction();
> }
> }
>
> and this other one b.js:
>
> // b.js
> function outterFunction() {
> //code here
> }
>
> module.exports = {
> someFunction: function() {
> innerFunction();
> }
> }
>
> NodeJS files are cached whenever we require them, that's so far so good, now my question is does the innerFunction in file a.js its also cached? or everytime I call
> require('a.js').someFunction() the function innerFunction is redefined?

Yes and no.

It's a new function each time, though the parsing and compilation of it is cached, inside the runtime. If you were to return that function and compare it with another call, though, they'd be different.

This probably doesn't have any practical implications though that you could care about.

Reply all
Reply to author
Forward
0 new messages