Object Oriented Programming with JavaScript

Posted on January 10, 2013

The Object Oriented web application can be written by using JavaScript. JavaScript supports inheritance as well as re-usability and encapsulation. Unlike other programming languages (JAVA, C++, PHP etc), JavaScript doesn’t contain class statement (no class keyword), is prototype based (instance-based) uses functions as classes. In JavaScript everything is object (except data types: Undefined, NULL, Boolean, Number and String) with some build in objects like Array, Date, Image, Object, Option etc. JavaScript object have properties and methods so it gives ability to create own objects with properties and methods.

As mentioned above there are many build in objects in JavaScript, although one can create JavaScipt object using new keyword like:


var obj = new Object();

obj. firstname = 'xyz';

obj. lastname = 'abc';

obj.func1 = function()

{

this.firstname = 'xyz';

this.lastname = 'abc';

}

We can create JavaScript objects with another simple way:


var obj = {

firstname = 'xyz';

lastname = 'abc';

func1 = function(){

this.firstname = 'xyz';

this.lastname = 'abc';

}

}

alert(Obj. firstname); // alerts xyz

obj. func1(); // calls func1

In above short example, we can see that JavaScript has power to add properties and methods to an object at run-time dynamically.