user2014743 user2014743 - 1 year ago 44
Node.js Question

Which way is better to pass function in javascript?

If I have 3 js files as follow:


this.functionName = function(params) { //do something};


function fucntionName(params) {
//do something

module.exports = {

Then in the third js file, I can require an object of the two files and make calls to the two functions defined in them; so for example if I call them in index.js

let file1 = require('/file1');
let file2 = require('/file2');

file1.functionName('some param');
file2.functionName('some param');

What are the difference between the two and which is preferred?

Answer Source

The first one-ish

As quoted from this post:

  • In the top-level code in a Node module, "this" is equivalent to module.exports.

Therefore the 2 may seem equivalent. But, they're not - in your second example, you are changing the object referenced by "module.exports". This is dangerous since any prior modifications that you have made to the original object previously referenced by "module.exports" within the same module (thanks Kevin for letting me know this wasn't clear) will no longer be available when requiring. In the future, should someone want to add a function using the other method, and make it available before your re-assignment, they might find themselves unable to access it while having some correct looking code.

Also - by allowing yourself to believe the 2nd method has the same effect, you may be tempted to do something like:

module.exports = {
// code, code, code
module.exports = {

Which will obviously strip you of acces to the original functionName1 method.

Of course, you may add both of the functions to the new object at the same time but what if they're just not available in your scope (e.g. they've been definied inside another function)? You'll still have to use the 1st method anyway at the time when the function is available.

Both methods obviously work. I am recommending the 1st one since to me it's both the clearer and less error prone.


Since this is context dependent, drop it all together and stick to module.exports. You'll end up with something like:

module.exports.functionName = function(params) { 
    //do something


function mySimpleFunction(params){
    //do something
module.exports.functionName = mySimpleFunction;

(in case your concern was with associating the declared function)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download