Last Updated: February 25, 2016
·
10.68K
· bhousman

Creating modules with getters and setters in Node

Modules helps sort Node apps into reusable pieces.

person.js

// These variables will stay in the local scope of this module (in this case, person.js)
var firstName, lastName, age;

// Make sure your argument name doesn't conflict with variables set above
exports.setFirstName = function (fname) {
    firstName = fname;
};

exports.setLastName = function (lname) {
    lastName = lname;
};

exports.setAge = function (yrsold) {
    age = yrsold;
};

// You're returning an object with property values set above
exports.getPersonInfo = function () {
    return {
        firstName: firstName,
        lastName: lastName,
        age: age
    };
};

app.js

var person = require('./person.js');

// Sets first name
person.setFirstName('Steve');

// Sets last name
person.setLastName('Jobs');

// Sets age
person.setAge(56);

// Outputs first name, last name, and age as an object literal
console.log(person.getPersonInfo());