JavaScript – Two function styles

There are two different styles of defining functions (and hence classes) in JavaScript. The first style is like defining a function variable. For example, you could define a class and a private method inside that class like this:

Person = function(fname, lname, age) {
...
    var getFirstName = function() {
    ...
    };
};

The second style is defining functions directly. So, the previous example becomes like this:

function Person(fname, lname, age) {
...
    function getFirstName() {
    ...
    };
};

Syntactically, I prefer the second style. It’s simpler and feels more natural. However, in my previous post about JavaScript classes, I used the first style for a reason. The reason is that even though you could use the second style for constructors and private methods, you cannot use it for privileged or public methods. You need to set privileged methods to “this” and public methods to protototype. So, the Person class from my previous post looks like this when I use the second style:

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

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

    // Private method
    function getFirstName() {
        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;
};

Notice how some functions are defined directly and some of them are defined as function variables. Even though this is not too bad, I prefer to stick with a single style, so I always go with the first style for consistency.

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