美文网首页
nodejs模块(暴露接口和引入模块)

nodejs模块(暴露接口和引入模块)

作者: dapaer | 来源:发表于2016-01-24 23:44 被阅读0次

1.建立一个模块

eg.Market.js

//---------------------------------------------------------------------------------------------------

function createMark(marketName){

this.marketName = marketName;

console.info('you create a market which name is '+this.marketName+'!!!');

function getMarketName (){

return this.marketName;

}

exports.createMark = createMark;

exports.getMarketName = getMarketName;

//---------------------------------------------------------------------------------------------------

eg. Main.js

//---------------------------------------------------------------------------------------------------

var mark = require('./Market.js');

mark.createMark('dapaer`s market');

console.info('mark`s name is ' + mark.getMarketName());

//---------------------------------------------------------------------------------------------------

通过exports去暴露模块的成员或方法(暴露公开的api)

有两种方式

1.module.exports.xxx = 模块里面的某个接口

2.exports.xxx = 模块里面的某个接口

这两者的区别

1.exports 是module.exports的引用指向同一个内存地址

2.require需要返回的是module.exports而不是exports,如果此时exports仍为module.exprots的引用则没有关系,如果不是则会报错。

           --》不是的情况:eg.exports = function(){xxx}或者exports = {}//一个新的对象,则会将原来的引用关系破裂,此时若是暴露module.exports = function(){xxx}或者module.exports = {}//一个新对象,不会报错,因为返回的仍然是require需要的。

通过require去加载模块

eg. var market = require('./Market.js')//.代表当前目录下

这段代码表达用require加载Market.js这个模块,返回了module.exports暴露出来的所有方法到market这个对象上

补充

所谓的引用是指指向同一个内存地址

eg. var personA = {Name:'TOM'};

      var personB = personA;

     此时personB是personA的引用

     如果此时将personB的属性Name 修改personA同样也会修改因为他们指向同一个内存地址,若此时将personB = {Name:'Candy'},则此时personA不会被改变,因为已将personB重新赋值,personB不再是personA的引用了,这里可以解释上的exports和module.exports的关系。

最后运行

相关文章

网友评论

      本文标题:nodejs模块(暴露接口和引入模块)

      本文链接:https://www.haomeiwen.com/subject/qygrkttx.html