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:
This is simple way to create an object using Object constructor.
This will produce following result
The other way of defining an object is via literal notation.
This will produce following result
The other way Factory function allows to encapsulate the logic for creating similar objects.
This will produce following result
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.
This will produce following result
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.
This will produce following result
The function/prototype combination takes advantage of both approaches.
This will produce following result:
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.
This will produce following result: