Hi Guys,
If you searched for classes in javascript ? then you are on the right place, Well like any other technology javascript also supports for oops but unfortunately it does not support for classes, Yes , Javascript is a class-less technology script.
We can simulate class behavior in javascript by creating an object for the function and then we can achieve behavior for accessing various methods of that function through the object created.
Lets take a look
Now we create an object for this function to access method like this
First we create object of Car then we set the year property and then accessed the method , all these are available only because its declared as public with 'this.' but we would not access value member as its declared privately, so here's we are achieving encapsulation by hiding the some members declared privately,which can be used for security purpose.
Please find the complete code on git here
If you searched for classes in javascript ? then you are on the right place, Well like any other technology javascript also supports for oops but unfortunately it does not support for classes, Yes , Javascript is a class-less technology script.
We can simulate class behavior in javascript by creating an object for the function and then we can achieve behavior for accessing various methods of that function through the object created.
Lets take a look
function Car( model ) {
var value=1; //private member
this.model = model; //all members with this are public
this.color = "silver";
this.year = "2012";
this.getInfo = function () {
return this.model + " " + this.year;
};
}
Now we create an object for this function to access method like this
function Run()
{
var myCar = new Car("ford");
myCar.year = "2010";
alert( myCar.getInfo() );
}
First we create object of Car then we set the year property and then accessed the method , all these are available only because its declared as public with 'this.' but we would not access value member as its declared privately, so here's we are achieving encapsulation by hiding the some members declared privately,which can be used for security purpose.
Please find the complete code on git here