Spider and web

Javascript - Object-oriented Programming

The features of object oriented programming are as follows:

  • Information hiding (Encapsulation)
  • Inheritance (i.e. polymorphism/late binding)

To implement all these features you need to use a few tricks - namely:

  1. Ignore the prototype mechanism.
  2. The use of closures.

As Javascript is not truly an object oriented programming language it is impossible to implement protected methods.

Prototype mechanism

The prototype mechanism requires that all variables to be public. The main motivation for object oriented programming is information hiding to reduce the possibility of an object getting into an erroneous state.

They implemented the prototype mechanism to reduce the memory footprint of Javascript. This is not an issue due to

  1. We are only using Javascript to make web pages interactive and thus not dealing with huge data structures.
  2. Modern parsers are able to optimise the script and reduce the memory requirements to a reasonable level.
  3. Modern computers have more than enough resources to handle repetition of compiled functions stored in the object.

Therefore I submit that this mechanism should be ignored. Our chief aim at using object oriented programming is to reduce the possibility of bugs.

Inheritance

To implement inheritance without the use of the prototype mechanism you need to adopt code as shown in the example below

function SubClass()
{
    var object = {};
    object.publicVar = 2;
    object.publicMethod = function SubClassPubMeth()
      {
        return this.publicVar + 2;
      };
    object.poly = function SubClassPoly()
      {
        return 'SubClassPoly';
      };
    return object;
}

function Class()
{
    var object = new SubClass();
    object.classPublicVar = 3;
    object.classPublicMethod =
        function ClassMethod()
        {
            return this.publicVar + this.classPublicVar;
        };
    object.poly = function ClassPoly()
      {
        return 'ClassPoly';
      };
    return object;
}

Here the code has all the features that are required. It is polymorphic and inherits the methods/variables from the sub-class.

Information hiding

To implement information hiding we can make use closures. The code below demonstrates this.

function Class()
{
    var object = {};
    object.x = 3;
    var privateVar = 3;
    function privateFunction(object)
    {
      return object.x + privateVar;
    }

    object.publicFunction = function()
      {
        var priv = privateFunction(this);
        priv += privateVar;
        privateVar = privateVar + 3;
        return priv;
      };
    return object;
}

Here we have a private variable and a private function.