54

I am new to Javascript and am seeing a lot of usage of exports and prototype in the code that I read. What are they mainly used for and how do they work?

//from express
var Server = exports = module.exports = function HTTPSServer(options, middleware){
  connect.HTTPSServer.call(this, options, []);
  this.init(middleware);
};

Server.prototype.__proto__ = connect.HTTPSServer.prototype;
Kiran Ryali
  • 1,371
  • 3
  • 12
  • 18
  • `export` keyword details [here](https://developer.mozilla.org/en/docs/web/javascript/reference/statements/export). Currently it is not supported natively by any of the web-browsers. – RBT May 01 '17 at 06:42

2 Answers2

23

Exports is used to make parts of your module available to scripts outside the module. So when someone uses require like below in another script:

var sys = require("sys");  

They can access any functions or properties you put in module.exports

The easiest way to understand prototype in your example is that Server is a class that inherits all of the methods of HTTPSServer. prototype is one way to achieve class inheritance in javascript.

nbro
  • 15,395
  • 32
  • 113
  • 196
Tom Gruner
  • 9,635
  • 1
  • 20
  • 26
  • 18
    but note that export, and modules in general, is not plain javascript, but an "extention" of node.js – Yannick Loiseau Mar 21 '11 at 16:06
  • 3
    Years went by and now it is a CommonJS modules pattern, not only for Node but in many other JavaScript environments. Including the browser thanks to polyfills and soon enough ES6 (the next JavaScript version) – Ivan Castellanos Jan 04 '14 at 01:25
  • 1
    @Yannick Loiseau `module` is `node` keyword And `export` is `javascript` keyword [javascript keyword list](http://www.w3schools.com/js/js_reserved.asp) – vijay Jan 18 '15 at 17:30
  • "is one way to achieve class inheritance in javascript." Are there more? – Ricardo May 31 '16 at 11:18
13

This video explains node.js module.exports and here is a resource which describes JavaScript prototype.

ruffin
  • 16,507
  • 9
  • 88
  • 138
yojimbo87
  • 65,684
  • 25
  • 123
  • 131