Object Oriented Programming in JavaScript

Published:

Add / read comments

Many web developers are using JavaScript to write mostly simple native or jQuery powered functions. But JavaScript provides options to build complex namespaces and objects by using object oriented programming.

Usually JavaScript only show/hide some part of web application or check form inputs by simple function. For example checking form input:

<script>
function checkInput ( elName )
{
  var el = document.getElementById(elName);
   console.log(el.value );
 
  if ( el.value.length < 3 ) {
    alert('Provide longer input ...');
  }
  else {
    alert('Provide is correct');
  }   
}
</script>

<input type="text" id="input" placeholder="provide input ..." />
<button onclick="checkInput('input');">Check input</button>

Or showing and hiding some informations using jQuery:

<script>
// DOM is ready
$(document).ready(function() 
{
  $('#info-button').click(function()
  {
    var __btn = $(this);
 
    $('#info-panel').toggle('slow', function( )
    {
      if ( $(this).is(':visible') ) {
        __btn.html('Hide info');
      }
 
      if ( $(this).is(':hidden') ) {
        __btn.html('Show info');
      }  
    });  
  });
});
</script>

<button id="info-button">Show info</button>
<div id="info-panel" style="display: none;">Information: this is some text</div>

There is nothing wrong by using as simple as possible and quickest solution, but if we want to write something more complex (like some class in PHP) we will need object oriented approach. And JavaScript is object-oriented to its core. Very beautifull article about objects in JavaScript.

I was always little bit confused about objects in JavaScript because JavaScript is a prototype-based language which contains no class statement, such as is found in PHP or Java. Instead, JavaScript uses functions as classes. Defining a class is as easy as defining a function. So I wrote some examples which made it clear to me. So let's create function Calculation:

/**
 * @param void
 * @return void 
 */
function Calculation () 
{  
  this.x = 0;
 
  this.y = 0;
 
  var i = 0;
}

Function is doing nothing so far. But we can create instance of an object by using the statement new and assign the result (which is of type obj) to a variable to access it later. Then we send the result into console to see the result.

var oInstance = new Calculation();
 
console.log( oInstance );

In the developer's console of your browser (usually press F12) will be displayed instance of an object. The biggest difference is, that variables X and Y are vissible from outside, but variable I is not. It's local variable which is accesible only inside the function. For example:

console.log( oInstance.x ); // output: 0
 
console.log( oInstance.i ); // output: undefined

Now let's add some functionality into the object:

/**
 * @param void
 * @return void 
 */
function Calculation () 
{  
  this.x = 0;
 
  this.y = 0;
 
  var i = 0;
 
  function isNumeric ( n ) 
  {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }
 
  this.square = function ( pa_i )
  {
     i = pa_i * pa_i;
     return i;
  }
 
  this.multiply = function ( pa_x, pa_y )
  {  
    if ( isNumeric(pa_x) && isNumeric(pa_y) )
    {
       this.x = pa_x;
       this.y = pa_y; 
       return 'Result is: ' + this.x * this.y;
    }
    else {
       console.log('Error'); 
    }
  }
 
};

So object now has methods for multiplying values and computing value powered by two. There is also another function isNumeric() which is local and can not be accessed from outside of object. This is very nice way to encapsulate function and not to pollute the global scope. Let's see how it works:

console.log( oInstance.square(3) ); // output: 9
console.log( oInstance.multiply(4, 3) ); // output: Result is: 12
console.log( oInstance.x + ' ' + oInstance.y ); // output: 4 3
console.log( oInstance.isNumeric(4) ); // output: TypeError: oInstance.isNumeric is not a function

As we can see, it is possible to access object properties and methods from outside and use and manipulate them also from inside of object. But there is also possibility to "hide" functions and variables to be accessed from outside.

There is also another way how to use object oriented programing in JavaScript. It's using namespaces. In JavaScript a namespace is just another object containing methods, properties and objects. There is no language-level difference between regular object and namespaces in JavaScript. Use of namespaces also minimizes the possibility of name conflicts in an application.

So let's create namespace with calculations:

CalculationSpace = {
  x: 1,
  y: 0,
 
  init: function()
  {  
    document.write('Initializing at: ' + window.location );  
  },
 
  square: function (pa_i)
  {
     i =  Math.pow(pa_i, 2);
     return 'Square of ' + pa_i + ' is: ' + i;
  },
 
  isNumeric: function(n) 
  {
    return !isNaN(parseFloat(n)) && isFinite(n);
  },
 
  multiply: function( pa_x, pa_y )
  {
    var result = false;
 
    if ( this.isNumeric(pa_x) && this.isNumeric(pa_y) )
    {
      this.x = pa_x;
      this.y = pa_y;
 
      result = 'Result is: ' + this.x * this.y;    
    }
 
    return result;  
  },
 
};

So namespace has also methods for multiplying values and computing value powered by two. There is one biggest difference between function and object and it is that method isNumeric can be accessed from outside of namespace. So all methods and properties are visible from outside, but they don't pollute the global scope because they are inside namespace.

Few examples:

console.log( CalculationSpace ); // output: object
CalculationSpace.init(); // output: will write into document your URL
console.log( CalculationSpace.square(8) ); // output: Square of 8 is: 64
console.log( CalculationSpace.multiply("8", 7) ); // output: Result is: 56
console.log( 'Value of x: ' + CalculationSpace.x  ); // output: Value of x: 8
console.log( 'Value of y: ' + CalculationSpace.y  ); // output: Value of y: 7
console.log( CalculationSpace.i ); // output: undefined

From last example you can see that there is way to hide some variables to be accessed from outside, but they must inside of namespace method.

Published:

Add / read comments

FIND ME

Share, follow or connect with me.