Thursday, March 17, 2011

Object Oriented Javascript

Hi,

OOP is not just limited to PHP, you can implement its concepts to some extent in javascript as well. But before I move on with it in details, the most important thing you need to understand about OOP as fas as Javascript is concerned is the fact, that there are no classes as such, as we have conventionally known. Here the functions are treated as class, which may contain member functions and data members.

Here is the javascript

<script type="text/javascript">
function Person(name)
{
  this.name = name;
  this.getName = getName;
  this.setName = setName;
}
function getName()
{
  return this.name;
}  
function setName(name)
{
  this.name = name;
}
var personObj = new Person('Bob');
alert('Name: ' + personObj.getName());
personObj.setName("John");
alert('Name: ' + personObj.getName());
</script>

In this I am creating a data type by the name "Person". Now I create an object of it as "var personObj= new Person('Bob');" note the argument that I am passing while initialising the object. This acts as a contructor of the function and initialises a property "name". Now i declare the getProperty and setProperty methods as "getName()" and "setName()".

getName() returns the property value. In our case it is Bob(initialized via constructor call) as follows:



Now I am calling the setName() function with argument, "John" as "person.setName("John");". Now when, again the getName() is called this is what we get:





That's it. It really is that simple. You just need to use the "this" keyword as and where required. You can create multiple objects of the same class as in PHP or any other OOP language.


No comments:

Post a Comment