require():使用module.exports vs直接分配给"this"

Kar*_*son 7 javascript node.js

我想知道在使用这两种方法时是否存在任何利弊:

first.js:

this.myFunction = function() {
    return 'herro first';
}
Run Code Online (Sandbox Code Playgroud)

second.js:

module.exports = obj = {};
obj.myFunction = function() {
    return 'herro second';
}
Run Code Online (Sandbox Code Playgroud)

然后将上面两个包括在内并如下使用:

app.js:

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

var second = require('./second');
console.log(second.myFunction());
Run Code Online (Sandbox Code Playgroud)

ᆼᆺᆼ*_*ᆼᆺᆼ 2

module.exports(或只是exports)是标准的 CommonJS 方式。

在 Node.js 中,this恰好是同一个对象,但最好不要依赖它,并且使用this不能与其他工具一起使用,例如 Browserify