Thursday, 19 February 2015

Constructor pattern in Javascript

Here I am going to explain on constructors, If you do not know C++, then please do not proceed further!!!

Objects are created from class/struct(C++), like wise Objects are created from "Constructor"( javascript).  
-------------------C++------------------  
Class Bus
{
      public:
      Bus( int model, int seatCapacity )
      {
          this.m_model = model;
          this.seatCapacity = seatCapacity;
       }
       private:
         int  m_model;
         int  seatCapacity;
  };
main()
{
    Bus   busObj( 4, 47 );
}
------------------------------------------

-----------------javascript------------
function Bus( model, seatCapacity)
{
    this.model = model;
    this.seatCapacity = seatCapacity;
}
var busObj = new Bus( 4, 47);
busObj.model = 5;//Access is graned to set 5 to "model" property.
------------------------------------------------

The limitation of Constructor patter in javascript is, you cannot hold private member variable. So you might me think that, how data encapsulation is taking place in JQuery or similar libraries ..Yes we have solution for that, that is what is called "Closure"

Note:

  • "new" keyword  is required in javascript to create the constructor, new is actually point to "this"
  • Use contructor, if you want to create 100's of similar objects.
  • there is no class in javascript


No comments:

Post a Comment