OBJECT CREATION PATTERNS IN JAVASCRIPT

 

So I am assuming that you are aware of the concept of Object-oriented programming in JavaScript. we’ll just brush up some basics here. Object is a data type in JavaScript that denotes any real world entity and has properties and methods. Properties are key value pairs and methods are functions that access and manipulate these properties and define the behavior of that object.


Properties can be accessed using the dot and bracket notation and methods need to be invoked using the dot operator. In this post we will discuss the object creation patterns in JavaScript.
The plain old objects can be created like:
var person ={};
person.name =”ajay”;
person.age = 24;
or like this:
var person ={
name: “ajay”,
age: 24
}
This is the object literal pattern for creating objects. We can also create a simple object like this:

var person = new Object();
person.name =”ajay”;
person.age = 24;


This is the object constructor pattern for creating objects. We can see that all three create a person object with two properties viz name and age. Object creation was easy but this approach is not very useful in practical scenarios where we usually need multiple instances of a type. So how do we create objects that can have multiple instances, surely not with the object literal or object constructor pattern. One answer could be to use a constructor function. A basic constructor function would look somewhat like this:


function Person(name, age){
this.name = name;
this.age = age;
this.showDetails = function(){
console.log(“Hi”);
}
return this;
}


Inside the constructor function, the keyword this references the new object that’s being created. We can now use the keyword new to create multiple instances of the person object like:
var p1 = new person(“Deepti”, 24);
we can now access person properties and methods through p1.
=> p1.name will give Deepti
We only have to make changes in the constructor function and they will be propagated to all the instances of the type. So a constructor function behaves like a class. What if we forget to use the new keyword while creating an instance,
var p2 = Person(“Divya”, 24);
We will still be able to access the person properties and methods but person will become a reference to the window object. This is in accordance with the binding standards of ‘this’ keyword to the global object.
Another way of creating objects is to use the prototype pattern. We will explore this and prototype chaining in our next post. Till then, Happy reading