Object-Orientated JavaScript

Object-oriented JavaScript for the C++ programmer.

This article presents a bestiary of JavaScript constructs, set against their equivalent in C++. Most of the basic class and object tools are available in JavaScript, and the syntax is often recognisably similar.

C++ is listed first in maroon followed by the corresponding JavaScript in dark green. For simplicity, C++ methods are defined inline.

Global variable:

  int global =0;
  var global =0;

Global function definition:

Note that the JavaScript syntax for a function definition is the same as a class definition:

  int globalfunction(int i, int j)
  {
      return 0;
  }
  function globalfunction(i,j)
  {
      return 0;
  }

Local variable:

A local variable uses the same syntax as a global, but it is declared within a function’s scope.

  void f()
  {
      int local =0;
  }
  function f()
  {
      var local =0;
  }

Local static variable:

  int f()
  {
      static int staticlocal=0;
      staticlocal++;
      return staticlocal;
  }
  function f()
  {
      if(typeof this.staticlocal == 'undefined')
          this.staticlocal=0;
      this.staticlocal++;
      return this.static_local;
  }

Class definition:

Note that the JavaScript syntax for a class definition is the same as a function definition. Use it as a class definition by calling it with the new keyword to make a new object.

  class C
  {
  };
  function C()
  {
  }

Create a new object:

The new operator is crucial to object orientated JavaScript. In this example, C can be called as a normal global function, but when called with new it becomes the constructor for a new Object.

  C* obj = new C();
  var obj = new C();

member variable – PUBLIC:

The example includes a class constructor that initialises the member variable.

  class C
  {
  public:
      int mpublic;
      C(int i): mpublic(i) {}
  };
  function C(i)
  {
      this.m_public = i;
  }

member variable – PRIVATE:

The example includes a class constructor that initialises the member variable. I don’t recommend using this in JavaScript – it works for simple classes, but breaks down if you try to use inheritance (JavaScript prototypes).

  class C
  {
      int mprivate;
  public:
      C(int i): mprivate(i) {}
  };
  function C(i)
  {
      var m_private = i;
  }

member variable – STATIC PUBLIC:

The example initialises the variable and also includes a class constructor that uses the variable.

  class C
  {
  public:
      static int mstatic;
      C()
      { 
          mstatic++;
      }
  };

int C::mstatic =0;

  function C(i)
  {
      C.mstatic++;
  }

C.m_static =0;

member function – PUBLIC:

The example is an accessor function for a private member variable.

  class C
  {
      int mprivate;
  public:
      C(int i): mprivate(i) {}
      int accessor() { return mprivate; }
  };
  function C(i)
  {
      var mprivate = i;
      this.accessor = function() { return m_private; }
  }

member function – PRIVATE:

  class C
  {
  private:
      void implementation() {}
  };
  // NO JAVASCRIPT EQUIVALENT

member function – STATIC PUBLIC:

The example is a simple factory function. Since the JavaScript function is defined outside the class, you cannot access any static private functions that the class may contain.

  class C
  {
  public:
      C() {}
      static C* factory() { return new C(); }
  };
  C* obj = C::factory(); // called from outside
  function C()
  {
  }
  C.factory = function() { return new C(); }
  var obj = C.factory(); // called from outside

member function – STATIC PRIVATE:

In Internet Explorer’s JavaScript, nested functions are indeed private. Firefox and Safari allow you to call these functions from outside, but you must specify the fully scoped name (e.g. C.sum(1,2);).

  class C
  {
  private:
      static int sum(int a, int b) { return a+b; }
  public:
      C() {}
  };
  function C()
  {
      function sum(a, b) { return a+b; }
  }

Side-by-side Summary:

C++ JavaScript
int global_variable =0;

int global_function(int i)
{
    global_variable += i;
    return global_variable;     
}

class C
{
private:
    int m_private;
    
public:
    int m_public;

    static int m_static;

    C(int i, int j):
        m_private(i),
        m_public(j)
    {
        m_static++;
    }

    int accessor()
    {
        return m_private;
    }

private:
    void implementation()
    {
    }

public:
    static C* factory()
    {
        return new C();
    }
};

int C::m_static =0;
var global_variable =0;

function global_function(i)
{
    global_variable += i;
    return global_variable;
}

function C(i,j)
{
    // (m_private not inheritable)
    var m_private = i;


    this.m_public = j;







    C.m_static++


    this.accessor = function()
    {
        return m_private;
    }


    function implementation()
    {
    }
} // end of C

C.factory = function()
{
    return new C();
}


C.m_static =0;

If you have any comments or corrections, then please leave a comment.

Comment · RSS · TrackBack

  1. Nir Tayeb said,

    8 July, 2005 @ 20:08

    for member private function do that:

    
    function C(){
      var mprivatefunc = function(){
      }

    this.getData = function(){ mprivatefunc(); } }

  2. Gabriel Boehme said,

    1 August, 2005 @ 21:46

    Check out http://www.crockford.com/javascript/private.html and http://www.litotes.demon.co.uk/js_info/private_static.html for techniques for creating private variables & methods in Javascript, and http://www.crockford.com/javascript/inheritance.html for further ways of duplicating classical inheritance within Javascript.

  3. Mark Koesel said,

    20 January, 2006 @ 18:08

    When not preceded with a class name in dot notation, nested functions in JavaScript are not static methods. By necessity, static methods can only access static members. Clearly nested functions can access instance members and thus they must not be static. They must, instead, be instance methods.

    FireFox and Safari may well allow these nested functions to be called as public static methods of the class. This means that these two userAgents have a namespace collision between public static methods and private instance methods. That is to say that, by declaring one, you automatically declare the other. What this means is that these methods will have undesired behavior when called in whichever context they were not designed for. However, we must point out that constructors in Javascript face the same dilema since they too can be called statically.

  4. Keith Hollingshead said,

    22 January, 2006 @ 16:08

    nice article!

  5. Andrey said,

    21 June, 2006 @ 09:56

    function C(){ this.getData = function(){ return true; } } better is function C(){} function C.prototype.getData() { return true; }

  6. gaba: Tűzfablog said,

    11 December, 2006 @ 19:56

    [...] Ha már ott voltam, körbenéztem a blogon. Szimpatikus hely. Van pl. egy érdekes cikk, ami a JavaScript objektumorientál vonásait vizsgálja meg a C++-hoz való hasonlítás segítségével: Object Orientated JavaScript [...]

  7. horst said,

    4 March, 2007 @ 14:34

    nope Andrey. It’s slower.

  8. Christian S. said,

    7 March, 2007 @ 17:58

    member function – PRIVATE:

    class C { private: void implementation() {} };

    // NO JAVASCRIPT EQUIVALENT

    Isnt it as follows??

    function C() { var implementation = function() { }; }

  9. af said,

    16 December, 2008 @ 03:52

    note that ‘this’ doesn’t refer to the function itself, but the object through which the function was invoked.

  10. _es said,

    25 January, 2009 @ 19:01

    Local static variable? “staticlocal” is GLOBAL variable – property.

    var id1 = function(){var n = 0; return function(){return n++;};}(); // or: with({n:0}) var id2 = function(){return n++;};

  11. Deepak said,

    29 March, 2010 @ 09:00

    Fantastic! Thanks.

Leave a Comment

Sponsors