Node.js - use of module.exports as a constructor

后端 未结 5 1932
孤城傲影
孤城傲影 2020-11-30 16:41

According to the Node.js manual:

If you want the root of your module\'s export to be a function (such as a constructor) or if you want to export a c

5条回答
  •  庸人自扰
    2020-11-30 17:11

    In my opinion, some of the node.js examples are quite contrived.

    You might expect to see something more like this in the real world

    // square.js
    function Square(width) {
    
      if (!(this instanceof Square)) {
        return new Square(width);
      }
    
      this.width = width;
    };
    
    Square.prototype.area = function area() {
      return Math.pow(this.width, 2);
    };
    
    module.exports = Square;
    

    Usage

    var Square = require("./square");
    
    // you can use `new` keyword
    var s = new Square(5);
    s.area(); // 25
    
    // or you can skip it!
    var s2 = Square(10);
    s2.area(); // 100
    

    For the ES6 people

    class Square {
      constructor(width) {
        this.width = width;
      }
      area() {
        return Math.pow(this.width, 2);
      }
    }
    
    export default Square;
    

    Using it in ES6

    import Square from "./square";
    // ...
    

    When using a class, you must use the new keyword to instatiate it. Everything else stays the same.

提交回复
热议问题