I'm new to node.js (and stackoverflow) and haven't found an exact explanation of this.
This is probably a trial answer but hopefully it'll help someone else who's also transitioning from Python/other object oriented frameworks.
I've seen other articles about what the prototype concept is in js and then others that explain the module.exports of node.js.
I'm studying the Ghost CMS and they use both. I can't seem to pick out why they would choose one over the other in certain cases.
Any help is appreciated, even if it's pointing me to other links.
When we want to export a single class/variable/function from one module to another module, we use the module. exports way. When we want to export multiple variables/functions from one module to another, we use exports way.
There is a clear reason why you should use prototypes when creating classes in JavaScript. They use less memory. When a method is defined using this. methodName a new copy is created every time a new object is instantiated.
Module exports are the instructions that tell Node. js which bits of code (functions, objects, strings, etc.) to export from a given file so that other files are allowed to access the exported code.
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.
With node.js, module.exports is how one exposes the public interface of a module.
/* my-module.js */
exports.coolFunction = function(callback) {
// stuff & things
callback(whatever);
};
This interface can then be consumed by another module after importing/requiring it:
/* another-module.js */
var myModule = require('my-module');
myModule.coolFunction(function(error) { ... });
Prototypes (a plain Javascript feature), on the other hand, are useful for defining shared properties and methods of objects instantiated from a constructor function.
function User() {
this.name = null;
}
User.prototype.printGreeting = function() {
console.log('Hello. My name is: ' + this.name);
};
var user = new User();
user.name = 'Jill';
user.printGreeting();
Cheers.
Actually they are interchangeable (in a way):
with prototype
:
//module.js
function Person (name) {
this.name = name;
}
Person.prototype.sayName = function () {
console.log(this.name);
}
module.exports = Person;
//index.js
var Person = require('./module.js');
var person = new Person('John');
person.sayName();
with exports
:
//module.js
exports.init = function (name) {
this.name = name;
return this;
}
exports.sayName = function () {
console.log(this.name);
}
//index.js
var Person = require('./module.js');
var person = Object.create(Person).init('John');
person.sayName();
The first example is more idiomatic for javascript, though.
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