JavaScript

Creating a class in JavaScript

It comes to a surprise that JavaScript, the most popular language on the web, has the most unconventional method for creating a class. In most object oriented programming languages, classes follow a common syntax. Here is one example:

class Person {
    private String fname;
    private String lname;

    public String className = "Person";

    public function __construct(fname,lname){
        this.fname = fname;
        this.lname = lname;
    }

    public function getFullName(){
        return this.fname + " " + this.lname;
    }
}

This is straight forward and coming from any language you will understand what is happening. Except in JavaScript, that's not how you create a class. The word class is a reserved keyword that still haven't found any use in the latest Ecmascript draft.

In JavaScript everything is an object. And that include Functions. And functions are classes...

Ok let me show you. To create a class, you create a function. But this function will be called differently. Let's rewrite our generic class above in JavaScript.

function Person(fname,lname) {

    // private variables
    var firstName = fname,
        lastName  = lname;

    // public variable
    this.className = "Person";

    this.getFullName = function() {
        return firstName + " " + lastName;
    }
}

This looks like a regular function. Using the keyword var we can create private members in the class. And with this, we can create public members. But the main difference occurs on the way we instantiate it.

var person = new Person("Ibrahim","Diallo");
person.getFullName();
> Ibrahim Diallo

When used with the keyword new, like in most languages, we instantiate the class. It may seem confusing at first, but this is just the way it is done in JavaScript, and if you familiarize yourself with it, you will see that it is not so different then other languages.

Note that we can also create Static Classes. It requires no complex naming convention. Let's try to recreate this class as a static one.

var Person = {
    fname: null,
    lname: null,
    className: 'Person',
    getFullName: function() {
        return this.fname + " " + this.lname;
    }
};

One key difference here is that we cannot create private variables. So when trying to decide which type of class you want to create, take this into consideration.


Comments(2)

Anon :

Can you put a date on your articles?

Ibrahim :

Thanks Anon, when the articles are old enough the date will be displayed. (2 years)

Let's hear your thoughts

For my eyes only