【Node.js】module.exports和exports的区别与使用
2017-07-15 15:06
726 查看
1.module.exports和exports的区别:
module.exports 初始值为一个空对象 {}
exports 是指向的 module.exports 的引用
require() 返回的是 module.exports 而不是 exports
2. 常见用法
module.exports在使用时,在一个js文件中只会有一条语句,否则第一条语句之后的表达式会将之前的赋值操作覆盖,如示例:
但是使用exports时,不会有数量限制。
3. js引用的特性决定了module.exports和exports的区别,所以一般情况下,module.exports用来导出类,exports用来导出方法,如示例:
app.js
var Cat = require("./cat.js")
var tool = require("./tool.js")
var cat = new Cat('baby');
console.log(tool.toUpperCase(cat.sing()))
cat.js
function Cat(name){
this.name = name;
this.sing = function(){
return "constructor: "+this.name+" want to walk.";
}
}
Cat.prototype.sing = function(){
return "prototype: "+this.name+" want to sing.";
}
Cat.prototype.walk = function(){
return "prototype: "+this.name+" want to walk.";
}
Cat.sing = function(){
return "function: "+this.name+" want to sing.";
}
module.exports = Cat;
tool.js
function toUpperCase (str){
return str.toLocaleUpperCase();
}
function toLowerCase(str){
return str.toLocaleLowerCase();
}
exports.toUpperCase = toUpperCase;
exports.toLowerCase = toLowerCase;
module.exports 初始值为一个空对象 {}
exports 是指向的 module.exports 的引用
require() 返回的是 module.exports 而不是 exports
2. 常见用法
module.exports在使用时,在一个js文件中只会有一条语句,否则第一条语句之后的表达式会将之前的赋值操作覆盖,如示例:
但是使用exports时,不会有数量限制。
3. js引用的特性决定了module.exports和exports的区别,所以一般情况下,module.exports用来导出类,exports用来导出方法,如示例:
app.js
var Cat = require("./cat.js")
var tool = require("./tool.js")
var cat = new Cat('baby');
console.log(tool.toUpperCase(cat.sing()))
cat.js
function Cat(name){
this.name = name;
this.sing = function(){
return "constructor: "+this.name+" want to walk.";
}
}
Cat.prototype.sing = function(){
return "prototype: "+this.name+" want to sing.";
}
Cat.prototype.walk = function(){
return "prototype: "+this.name+" want to walk.";
}
Cat.sing = function(){
return "function: "+this.name+" want to sing.";
}
module.exports = Cat;
tool.js
function toUpperCase (str){
return str.toLocaleUpperCase();
}
function toLowerCase(str){
return str.toLocaleLowerCase();
}
exports.toUpperCase = toUpperCase;
exports.toLowerCase = toLowerCase;
相关文章推荐
- Node.js模块导出exports 和 module.exports 的区别
- Node.js模块导出exports 和 module.exports 的区别
- Node.js中exports与module.exports的区别
- node.js 中exports和module.exports的区别
- Node.js的模块导出exports 和 module.exports 的区别
- Node中Exports与module.export的使用与区别
- node.js module初步理解,exports与module.exports的区别
- Node.js中exports与module.exports的区别
- node.js中module.exports与exports的区别
- Node.js中module.exports与exports的区别
- node.js中exports与module.exports区别
- Node.js Module – exports 和module.exports之间的联系与区别
- Node.js中exports与module.exports的区别
- Node.js中exports与module.exports的区别
- nodejs exports和module.exports的区别
- Node.js 中exports 和 module.exports 的区别
- Node.js: exports与module.exports的区别
- node.js中的exports和module.exports的区别
- nodejs exports和module.exports区别
- Node.js模块导出exports 和 module.exports 的区别