zoukankan      html  css  js  c++  java
  • [Node.js] Exporting Modules in Node

    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.

  • 相关阅读:
    leetcode931
    leetcode1289
    leetcode1286
    poj Meteor Shower
    noip杂题题解
    noip2007部分题
    NOIP Mayan游戏
    某模拟题题解
    codevs 1423 骑士
    noip 邮票面值设计
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5582631.html
Copyright © 2011-2022 走看看