Monday, March 26, 2012

JavaScript and OOP


Following the introductory blog about JavaScript, I am now evolving more into JavaScript in relation to object oriented programming. JavaScript supports Object Oriented Programming because it supports inheritance through prototypes, properties and methods. Some people do not realize that JavaScript supports inheritance. JavaScript syntax is similar to the syntax of Java and C#. The fact that JavaScript supports inheritance and thus making it an Object Oriented Language, gives the developers of JavaScript power. Code can be written once and be used again, while supporting encapsulation.

Why are objects great?

Objects created in JavaScript act like real life objects and they have properties and methods. People, animals, cars and furniture all have properties. Properties of human beings are height, for example with a value of 160cm. Methods of people can be speaking or running. Methods can also change properties, such as eating and gaining weight.

JavaScript enables developers to create their own objects for their applications. Objects allow programmers to code events that respond to actions by the end user. Objects can be initialized any number of times, and also with different values.

Creating objects using the new operator

There are two ways to create objects in JavaScript. One of the most common methods is to use the new operator. The syntax for this is to use the new Object(); piece of code.    This works by first declaring the new Object, and then adding the properties to this object.

01
person = new Object();
02
person.name = “Daniel”;
03
person.surname = “Borg”;
04
person.age = 24;

The code snippet above show a new person object being created and then the properties name, surname and age are created and assigned a value. Apart from properties we can also create methods assigned to that object. This can be seen in the code snippet below:

05
person.talk = function () {
06
     this.state = “talking”;
07
     this.volume = “high”;
08
}

Above we can see that a person can do a method talk and during that method he will be talking with high volume. However, this is not the only way to create an object.

Creating objects using the literal notation

Another way is to create the object in literal notation. This feature is supported from version 1.2 onwards. It is more robust and can be easier to create an object on the fly using this method. As an example we can create the same object but using literal notation.

01
person = {
02
     name: “Daniel”,
03
     surname: “Borg”,
04
     age: “24”,
05
     talk: function () {this.state = “talking”}
06
};

This code above is exactly the same as the previous code but in literal notation. However, both examples here cannot be reused.

Object Constructor and Prototyping

The best way to create an object would be to use the Object Constructor Function. The object constructor is very robust since it is a JavaScript function. It can define parameters and call other functions, amongst other features. The difference between the other method and the method using constructor is that a constructor function is called via the new operator. Now I will create a function used as an object constructor. The properties and methods of the object are declared within this function by using the prefix this.  New objects are created using the object constructor by using the new keyword. Using this method we can create multiple objects.

01
function dog(name) {
02
     this.name = name;
03
     this.talk = function () {
04
          alert(this.name + “ said Woof!!”;
05
     }
06
};
07
dog1 = new dog(“Aslan”);
08
dog1.talk();
09
dog2 = new dog(“Butch”);
10
dog2.talk();

The code above shows the same object constructor used to create two different objects with the same code.

Prototyping

Prototyping is a more elegant approach to add a method to the constructor function. It is a type of inheritance in JavaScript. Prototyping can be described by a particular race learning a particular method and then all members of that race will be able to use that method.

01
dog.prototype.changeName = function(name) {
02
     this.name = name;
03
}

The code above adds the method changeName to all instance of a dog. Using the code below will generate “Snowy said Woof!!” instead of “Aslan said Woof!!”.

01
dog1.changeName(“Snowy”);
02
dog1.talk();

This shows that after that method was added, all instances of dog were able to use that method.

Sub and Super Classes

We already saw that JavaScript supports prototype inheritance. However, C# and Java contain an explicit concept of class hierarchy in the sense that every class can have both a super class and a sub class. The super class is from where the class inherits the properties and the methods. On the other hand, a class can be extended to other subclasses which inherit the methods and properties from the parent’s behaviour. JavaScript prefers to use prototype but it is still possible for inheritance to take place in other ways.
The example below shows this more clearly.

01
function superClass() {
02
     this.supertest = superTest;
03
}
04
function subClass() {
05
     this.inheritFrom = superClass;
06
     this.inheritFrom();
07
     this.subtest = subTest;
08
}
09
function subtest() {
10
     return “SuperTest”;
11
}
12
var newClass = new subClass();
13
alert(newClass.subtest());
14
alert(newClass.supertest());

Here we created two classes, superClass and subClass. superTest() was attached to the superClass while subTest() was attached to subClass. Line 05 states that the subClass should inherit from the superClass. To test this out, two alerts were created, both calling methods from the instance of the subClass. However, the second alert is calling a function which is written within the code of the superClass. This is available to the subClass through inheritance from the superClass.

Now we have a better understanding of how objects work in JavaScript and how we can use objects to help us write less code to achieve more results.

No comments:

Post a Comment