您的位置:首页 > Web前端 > Node.js

【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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息