一个node.js文件就是一个模块,这个文件可能是js代码,json或者编译过的C/C++扩展
//a.js
var name;
exports.setName = function(thyName){
name = thyName;
};
exports.sayHello = function(){
console.log("hello"+name);
};
//b.js
var myModule = require('./a.js');
myModule.setName('柠檬不酸');
myModule.sayHello();
第一种
function Hello(){
var name;
this.setName = function (thyName){
name=thyName;
}
this.sayHello = function(){
console.log('hello'+name)
}
}
exports.Hello=Hello;
var Hello = require('./c.js').Hello;
hello = new Hello();
hello.setName('柠檬不酸le');
hello.sayHello();
第二种
//c.js
function Hello(){
var name;
this.setName = function (thyName){
name=thyName;
}
this.sayHello = function(){
console.log('hello'+name)
}
}
module.exports = Hello;
//d.js
var Hello = require('./c.js');
hello = new Hello();
hello.setName('柠檬不酸');
hello.sayHello();
注意:不可以通过exports 直接赋值代替对module.exports赋值;
exports实际上只是一个和module.exports指向同一个对象的变量,它本身会在模块执行结束后释放,但module不会,因此只能通过指定module.exports来改变访问接口;
原文:https://www.cnblogs.com/foreverLuckyStar/p/12076111.html