require():使用module.exports vs直接分配给“this”
16lz
2021-01-22
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());
1 个解决方案
#1
2
module.exports
(or just exports
) is the standard CommonJS way.
module.exports(或只是导出)是标准的CommonJS方式。
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
在Node.js中,这恰好是同一个对象,但最好不要依赖它,并且使用它不能与其他工具一起使用,例如Browserify
更多相关文章
- Javascript学习:案例7--对象属性和方法的遍历、删除、添加.html
- Javascript正则表达式对象和美元符号
- 将JavaScript对象转换为要插入关系数据库的数组
- Javascript对象
- javascript数组和对象是否有设置顺序?
- JavaScript初探系列之面向对象
- 将对象值传递给指令而不是任何其他数据变量
- 对象的属性也要加引号吗
- 在javascript中过滤对象对象(过滤还是减少?)