How to make c++ like classes in Javascript

This post discusses how to write classes in Javascript if you have mostly c++ background.

I have coded c++ for whole my professional career, so I am used to type-safety, strict definitions and object-orientation. When I started coding Javascript, I first found it quite a “loose” language, but on the other hand I have found it to be really really flexible and easy to write – when you know what you are doing. Javascript even has many features that c++ doesn’t. For example unnamed functions (closely related to concept called “closure”) are very common in Javascript code. Lambda functions were added to c++ only recently and even then they seem a bit overly complex when compared to what Javascript does. But to the point:

In Javascript, you instiate an object in similar manner than in c++:

var dog = new Dog("Pat");
var name = dog.getname();

But in Javascript there is no such thing as class declaration. Instead, you define a constructor function, which initializes all the object’s member variables and methods. You can think this function definition as the class declaration and you can write it to look like one (since you as the c++ coder like strict definitions):

// class Dog
function Dog(name)
{
  this.name = name;  // Name of the dog

  this.getname = function ()
  {
    // Get name of the dog
    if (this.name != undefined)
      return this.name;
    else
      return "no name";
  };
}

Notice what actually happens: you are not declaring the class that will be created as an object (as in C++), but you are actually creating the object structure dynamically when the constructor is being called. From Javascript perspective it would be perfectly fine to add members and methods even later from outside the constructor, but you may consider if that is really a wise thing to do.

You can specify any number of parameters as for any function. You never return anything from this function (since it is always called with the New syntax). You can also make multiple constructors with different parameters, but then you must yourself make sure the constructors are in perfect sync and all create the same kind of object (or call one from the other and make more initializations on top). Further, these functions must have different names, because Javascript doesn’t support function overloading, so it is a bit unconvenient.

Inheritance can also be done, but there is a trick:

// class Animal
function Animal(name)
{
  // Animal things...
}

// class Dog : Animal
function Dog(name)
{
  // Call the base
  Animal.call(this,name);
  // Dog things...
}

As you can see, the Dog constructor calls the base class Animal constructor as the first thing (as would c++). Notice that normal function call “Animal(name);” would not work, because it would use the wrong thing as “this”. This special calling convention in Javascript allows to specify what “this” should refer to.

  

Comments are closed.