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;
The export statement is used when creating JavaScript modules to export objects, functions, variables from the module so they can be used by other programs with the help of the import statements. There are two types of exports. One is Named Exports and other is Default Exports.
Every object in JavaScript has a built-in property, which is called its prototype. The prototype is itself an object, so the prototype will have its own prototype, making what's called a prototype chain. The chain ends when we reach a prototype that has null for its own prototype.
prototype is a property of a Function object. It is the prototype of objects constructed by that function. __proto__ is an internal property of an object, pointing to its prototype.
With the help of ES6, we can create modules in JavaScript. In a module, there can be classes, functions, variables, and objects as well. To make all these available in another file, we can use export and import. The export and import are the keywords used for exporting and importing one or more members in a module.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With