JavaScript can create objects in more than one way. Following are the list of patterns and examples:

Listed patterns

Object can be created as a name-value pairs. Once object is created properties can be added to the object. We can create empty object by not having any prototype or methods within {}.

Example of listed pattern

Factory patterns

Factory pattern is used when object to be instantiated is known at run-time. It does not use the keyword new while creating object. This method makes code easy through interface. This makes the code to be re-used which require similar re-instantiation. Disadvantage of this is unit testing is difficult.

Example of factory pattern

Below function outputs the continent for the given country name. The object for respective continent is created depending on country selected. Here factory method becomes relevant.

Constructors

Object can be created using new keyword. The object name has capital letter in the first word. Constructor is the function with required prototypes and methods. Any number of objects can be created with it.

Example of constructors

function Animal(name, food, type) {
    this.name = name;
    this.food = food;
    this.type = type;
}
var lion = new Animal(“Lion”, “Meat”, “Wild”);

Read more about constructor here...

Prototypes

All the JavaScript objects have a prototype. Prototypes are basically objects. It can allow user to add properties and methods to object, after object is created. Objects created from new Object() inherits Object.prototype which can be over-ridden. Similarly, objects created from new Animal() has new Animal() prototype. 

Prototype is created with constructor function. Object.create() is used to create new object with required prototype object and properties.

Creating null objectvar Animal = Object.create(null);

To get prototype of Object:  Object.getPrototypeOf(Animal); // Returns constructor

Example of prototypes

Read more about prototypes here...

 

›› go to examples ››