Tuesday, March 3, 2015

Object Oriented Programming in JavaScript (Class in JavaScript)


Hello All, I would like to explain OOPs concept here which are very useful while using JavaScript for a large project. Object oriented concept in JavaScript is very useful in case you are creating modules in your project. Before starting I would like to cover few basic things about JavaScript. Class in JavaScript is nothing but function. There are 2 ways to create object of a class in JavaScript:
  • Using Object.create (Prototypal Model)
  • Using new keyword (Classical Model)

Using Object.create (Prototypal Model)

var TilePrototype = {
   constructor: function(header,value) {
      this._header = header;
      this._value = value;
   },
   render: function(){
      // Your code here to create tile using header and value;
   }
}

var myTile = Object.create(TilePrototype); // Here you created object of TilePrototype
myTile.constructor("My first tile", "Some value"); // Initialize the value using constructor
myTile.render(); // Call render method to create tile

Now how to achieve inheritance using Object.create

   var AdvancedTilePrototype = Object.create(TilePrototype);
   AdvancedTilePrototype.render = function(){
      TilePrototype.render.call(this);
      // add some more advanced functionality here which will be extended including parent class method. 
   }
  // Now any one can create object of this child class
  var myAdvancedTile = Object.create(AdvancedTilePrototype);
  myAdvancedTile.constructor("My advanced tile","value");
  myAdvancedTile.render();

Using new keyword (Classical Model)

  function Tile(header,value){
    this._header = header;
    this._value = value;
  }
  Tile.prototype.render = function(){
    // Your code here to create tile using header and value;
  }
  var myTile = new Tile("My first tile", "some value"); // create new object of Class Tile
  myTile.render(); // Call render method to render tile

Now how to achieve inheritance in this classical model

  function AdvancedTile(header, value){
    Tile.call(this, header, value);
  }
  AdvancedTile.prototype = Object.create(Tile.prototype);
  AdvancedTile.prototype.constructor = AdvancedTile;
  AdvancedTile.prototype.render = function(){
    Tile.prototype.render.call(this);
    // add your advanced code
  }

No comments:

Post a Comment