elloworld111
elloworld111

Reputation: 255

Javascript Modules: Prototype vs. Export

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.

Upvotes: 11

Views: 22753

Answers (2)

vkurchatkin
vkurchatkin

Reputation: 13570

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.

Upvotes: 21

heyheyjp
heyheyjp

Reputation: 626

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.

Upvotes: 10

Related Questions