Kaarel Purde
Kaarel Purde

Reputation: 1265

What is a context safe way to call functions within module.exports?

I have this in my JS file:

module.exports.function1() {};

module.exports.function2() { this.function1(); };

module.exports.function3() { module.exports.function1(); };

Which is the preferred way to invoke other functions from module.exports - function2() or function3() way? Or is there a better way?

I don't like function2() way because it's not context safe and function3() way looks kinda weird to me.

Upvotes: 0

Views: 52

Answers (1)

mdickin
mdickin

Reputation: 2385

Personally, I prefer to declare the exports up top and then put the declarations below

module.exports = { 
    function1: function1, 
    function2: function2,
    function3: function3
}
function function1() { }
function function2() { function1(); }
function function3() { function1(); }

Edit I do it this way so that the function declarations can reference each other without having to go through module.exports or anything. Since it's in a module, it's self contained. Also, when you open the file, you get a clear look at the exports without having to wade through all the implementation first.

Upvotes: 3

Related Questions