nj05---模块

概念:模块(Module)和包(Package)是Node.js最重要的支柱。在浏览器JavaScript中,脚本模块的拆分和组合通常使用HTML的script标签来实现,Node.js提供了require函数来调用其他模块,而且模块都是基于文件,模块和包的区别是透明的(java里面的model层server层分的很细,nj没有用的是模块的包),因此经常不作区分。

一、模块
1.什么是模块
一个Node.js文件就是一个模块,这个文件可能是JavaScript代码、JSON或者编译过的C/C++扩展。
var http=require('http'),其中http是Node.js的一个核心模块,通过require函数获取这个模块,然后使用其中的对象

2.创建及加载模块
(1)创建模块
Node.js提供了exports和require两个对象,其中exports是模块公开的接口,require用于从外部获取一个模块的接口,即获取模块的exports对象
附件module.js和getModule.js的实现

(2)单次加载
上面的例子有点类似创建一个对象,但实际上和对象又有本质的区别,因为require不会重复加载模块,也就是说无论调用多少次require,获取的模块都是同一个(不同的变量指向的是同一个对象的引用)
getModule2.js

module.js

//一个js文件就是一个类,有属性,和public方法
var name;
exports.setName=function(thyName){
    name=thyName;
}
exports.sayHello=function(){
    console.log('hello'+name);
}

getModule.js

var myModule=require('./module');
myModule.setName('marico');
myModule.sayHello();

getModule2.js

var myModule1=require('./module');
myModule1.setName('marico');
var myModule2=require('./module');//不同变量指向同一个引用
myModule2.setName('yfc');

myModule1.sayHello();
myModule2.sayHello();
(3)覆盖exports
有时我们知识想把一个对象封装到模块中,例如
定义模块:singleobejct.js
引入模块使用:getSingleObject.js
繁琐:exports.hello=hello;
引入:require("./singleobject").hello;
简易:module.exports=hello;
exports本身仅仅是一个普通的空对象,即{},它是专门用来声明接口

singleobject.js

function hello(){//
    var name;
    this.setName=function(thyName){
        name=thyName;
    }
    this.sayHello=function(){
        console.log('hello '+name);
    }
}
//exports.hello=hello;//麻烦,需要var hello = require("./singleobject").hello;
module.exports=hello;

getSingleObject.js

var hello=require('./singleobject');
var he=new hello();
he.setName('marico');
he.sayHello();
var he2=new hello();
he2.setName('yfc');
he2.sayHello();
原文地址:https://www.cnblogs.com/yaowen/p/7012780.html