Javascript Modules: Prototype and Export

I am new to node.js (and stackoverflow) and have not found an exact explanation for this.

This is probably a test answer, but hopefully it will help someone else who will also move from Python / other object-oriented frameworks.

I saw other articles about the prototype concept in js and then about others that explain module.exports node.js.

I am learning Ghost CMS and they use both. I can’t understand why in some cases they choose each other.

Any help is appreciated even if it points me to other links.

+4
source share
2 answers

node.js, module.exports , .

/* my-module.js */

exports.coolFunction = function(callback) {

    // stuff & things
    callback(whatever);
};

/:

/* another-module.js */

var myModule = require('my-module');

myModule.coolFunction(function(error) { ... });

Prototypes ( Javascript), , , .

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();

.

+3

( ):

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();

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();

javascript.

+8

Source: https://habr.com/ru/post/1528147/


All Articles