码迷,mamicode.com
首页 > Web开发 > 详细

[Node.js] Exporting Modules in Node

时间:2016-06-14 06:27:00      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:

In this lesson, you will learn the difference between the exports statement and module.exports. Two examples are demonstrated, each accomplishing the same task but one using export statements and one using module.exports. You will also learn the basic thumb rule to identify which is appropriate for your current needs.

// circle.js using the exports statement
var PI = Math.PI;

exports.area = function(r){
  return PI * r * r;
}

exports.circumference = function(r){
  return 2 * Pi * r;
}

 

// accessing the exported functions in the node shell
var circle = require(‘./circle.js‘);

circle.area(4);
circle.circumference(4);

 

---------------------

// using module.exports to demonstrate the same functionality
var PI = Math.PI;

module.exports = function(r){
  return {
    area: function(){
      return PI * r * r;
    },
    circumference: function(){
      return 2 * PI * r;
    }
  }
}

 

// accessing the exposed functions in the node shell
var circle = require(‘./circle.js‘);

var myCircle = circle(4);

myCircle.area();
myCircle.circumference();

To summarize that, the general thumb rule is use the exports statement to export instances of modules. Use the module.exports statement to export JavaScript objects.

[Node.js] Exporting Modules in Node

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5582631.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!