Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

require(): using module.exports vs assigning to "this" directly

I'm wondering if there are any pros or cons when using the two approaches against each other:

first.js:

this.myFunction = function() {
    return 'herro first';
}

second.js:

module.exports = obj = {};
obj.myFunction = function() {
    return 'herro second';
}

The two above would then be included and used as so:

app.js:

var first = require('./first.js');
console.log(first.myFunction());

var second = require('./second');
console.log(second.myFunction());
like image 598
basickarl Avatar asked Feb 01 '16 00:02

basickarl


1 Answers

module.exports (or just exports) is the standard CommonJS way.

In Node.js, this happens to be the same object, but that is best not relied on, and using this will not work with other tools, for example Browserify

like image 125
ᅙᄉᅙ Avatar answered Oct 06 '22 01:10

ᅙᄉᅙ