Javascript Object Oriented Programming

Javascript is very simple to use in term of object oriented programming, compaired to other "pure" object oriented languages such as c++, Java, C# etc. Javascript has a number of built in objects that allows to create new objects and properties. User can create new object by creating instance of the object.

Javascript object is a simple collection of properties, properties nothing but key-value pair. Here value can be any primitive type, an object, or a function. Javascript properties can be added, updated and deleted at any point of time. The general format of creating an object in Javascript using an object initializer are

Where "objectName" is the name of object and propertyX:valueX is the name value pair. There are different way to create object in Javascript:

Using Object Constructor

This is simple way to create an object using Object constructor.

Javascript Using Object Constructor Example

This will produce following result

Using Literal Notation

The other way of defining an object is via literal notation.

Javascript Using Literal Notation Example

This will produce following result

Using Factory Function

The other way Factory function allows to encapsulate the logic for creating similar objects.

Javascript Using Factory Function Example

This will produce following result

Using Object Constructor

In Javascript functions are objects, you can call any function using the new operator in front of it. It would be nice if all instances of Person share the same displayPerson object, since this holds behavior and not data.

Javascript Using Object Constructor Example

This will produce following result

Using Prototype

In Javascript functions are objects, they can create other objects and they automatically get a field called prototype. Every object created through a function inherits the function's prototype.

Javascript Using Prototype Example

This will produce following result

Using Combination of Function/Prototype

The function/prototype combination takes advantage of both approaches.

Javascript Using Combination of Function/Prototype Example

This will produce following result:

Using Singleton

Sometimes, you may need to make sure that only a single instance of a certain object exists. In Javascript you can simply define and invoking the constructor at the same time.

Javascript Using Combination of Function/Prototype Example

This will produce following result: