11-《Node.js开发指南-模块和包

什么是模块?

一个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来改变访问接口;

创建包

包是在模块基础上更深一步的抽象,它将某个独立的功能封装起来,用于发布,更新,依赖管理和版本控制

Node.js的包是一个目录,其中包含一个JSON格式的包说明文件package.json

猜你喜欢

转载自www.cnblogs.com/foreverLuckyStar/p/12076111.html