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

node.js中exports和module.exports的使用

2018-01-30 15:29 417 查看
每一个node.js文件,都有一个module对象,而每一个module对象都有一个初始化值为 {} 的 exports 属性。

node.js导出模块可以用以下两种方法:

//方法一
exports.aaa = xxx;

//方法二
module.exports = xxx;


方法一:

导出模块moduleA.js

var obj = {
name:"scy"
}

exports.obj = obj;
exports.c = obj;
exports.num = 19;


导入模块runA.js

const moduleA = require("./moduleA");

console.log(moduleA);//{ obj: { name: 'scy' }, c: { name: 'scy' }, num: 19 }
console.log(moduleA.obj);//{ name: 'scy' }
console.log(moduleA.c);//{ name: 'scy' }
console.log(moduleA.num);//19
console.log(moduleA.ss);//undefined


方法二:

moduleB.js

function Person() {
this.name = "scy";
this.age = 19;
this.getName = function () {
return this.name;
}
}
Person.prototype.getAge = function () {
return this.age;
}
module.exports = Person;


runB.js

const Person = require("./moduleB");

const person = new Person();
console.log(person);//Person { name: 'scy', age: 19, getName: [Function] }
console.log(person.getName());//scy
console.log(person.getAge());//19


注:

//导出
module.exports = {
a:19
}
exports.a = 100;

//导入
const a = require("./moduleC");
console.log(a);

//结果
19


两个方法可以这样用:

//导出
var exports = module.exports = {
a:19
}
exports.a = 100;

//导入
const a = require("./moduleC");
console.log(a);

//结果
100
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: