JavaScript – Class and Visibility Control

Classes and visibility control in JavaScript are a little different from the traditional object oriented languages like Java. Here’s a simple JavaScript class I use as a cheat-sheet from time to time to remind myself the JavaScript syntax.

// Constructor
Person = function(fname, lname, age) {

    // Private variables
    var _fname = fname;
    var _lname = lname;
    var _age = age;

    // Private method
    var getFirstName = function() {
        return _fname;
    };

    // Public variable
    this.fullName = fname + ' ' + lname;

    // Privileged method - exposes private variables and methods publicly.
    this.getFirstNameAndAge = function() {
        return getFirstName() + ", " + _age;
    };

    Person.numberOfPeople++;
};

// Public static variable
Person.numberOfPeople = 0;

// Public method
Person.prototype.getFullNameAndNumberOfPeople = function () {
    return this.fullName + " --> " + Person.numberOfPeople;
};

And here’s the test output for the class:

var person = new Person('Mete', 'Atamel', 29);
var person2 = new Person('John', 'Smith', 50);
console.log(person._fname); // undefined
console.log(person.fullName); // Mete Atamel
console.log(person.getFirstNameAndAge()); // Mete, 29
console.log(Person.numberOfPeople); // 2
console.log(person.getFullNameAndNumberOfPeople()) // Mete Atamel --> 2
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s