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

后端 未结 5 1942
孤城傲影
孤城傲影 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:18

    This question doesn't really have anything to do with how require() works. Basically, whatever you set module.exports to in your module will be returned from the require() call for it.

    This would be equivalent to:

    var square = function(width) {
      return {
        area: function() {
          return width * width;
        }
      };
    }
    

    There is no need for the new keyword when calling square. You aren't returning the function instance itself from square, you are returning a new object at the end. Therefore, you can simply call this function directly.

    For more intricate arguments around new, check this out: Is JavaScript's "new" keyword considered harmful?

提交回复
热议问题