You've successfully subscribed to Smartcodehub ™ Blog
Great! Next, complete checkout for full access to Smartcodehub ™ Blog
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Create Objects in javascript

Create Objects in javascript

. 5 min read

Their are various ways to create objects in JavaScript we will look at some of them

so lets start from scratch  the basic way to create an object is

var object = {}

var car = {}

and now if we want to add certain properties to it lets say a name and color so we will say

car.name = "Thar"
car.color = "gray"

simple right we have a object car with two properties name and color .

Lets add few functions also to it like

car.start = function(){
    console.log('car is starting')
}

car.stop = function(){
    console.log('car is stoping')
}

now lets say if we want to have multiple cars then we will end up writing the code again and again so lets  extract the code of creating the car in a new function


function Car(name,color){
    var car = {};
    car.name = name;
    car.color = color;
    car.start = function(){
        console.log('car is starting');
    }
    car.stop = function(){
        console.log('car is stoping');
    }

    
    return car;
}

so now if want to have multiple object we can say

var thar = Car("Thar","grey");
var swift = Car("Swift","white");

so it worked but their is one problem with it when ever you create a new car it creates the four functions in memory  and can be a memory leak

so wont it be good if we create that functions one and just assign them to new car object what i mean is

var CarUtils = {
start : function(){
    console.log('car is starting')
},

stop : function(){
    console.log('car is stoping')
}

}

and now in our Car function


function Car(name,color){
    var car = {};
    car.name = name;
    car.color = color;
    car.start = CarUtils.start;
    car.stop = CarUtils.stop;
    return car;
}

ok so seems like the problem is solved but now we have one another problem lets say if i want to add a new meathod then i have to first add it to car utils object and then update my car function to have it as a property

var CarUtils = {
    start : function(){
        console.log('car is starting')
    },

    stop : function(){
        console.log('car is stoping')
    },
    move : function(){   // the new function
        console.log('car is moving')
    }
}


function Car(name,color){
    var car = {};
    car.name = name;
    car.color = color;
    car.start = CarUtils.start;
    car.stop = CarUtils.stop;
    car.move = CarUtils.move;
    return car;
}

so what we basically want is when we create the car object it should have all the functions of the carutils object as its properties for that we will use another way of creating object that is

Object.create()

Object.create() method is used to create a new object with the specified prototype object and properties. Object.create() method returns a new object with the specified prototype object and properties.

the syntax is

Object.create(prototype[, propertiesObject])

var CarUtils = {
    start : function(){
        console.log('car is starting')
    },

    stop : function(){
        console.log('car is stoping')
    },
    move : function(){   // the new function
        console.log('car is moving')
    }
}
function Car(name,color){
    var car = Object.create(carUtils);
     // so at this point our car object will have three functions
     // associated with it like start,stop and move
    car.name = name;
    car.color = color;
    
    
    we will no more do it ourself
   // car.start = CarUtils.start;
   // car.stop = CarUtils.stop;
   // car.move = CarUtils.move;
    return car;
}

OK so now the problem is resolved but wait our application is growing and we have more types like car , bike ,trucks and many more so do we really have to make a object like car Utils and maintain it well this is a very frequently appearing problem so JavaScript has already given us a solution for that  .

so rather then us creating a carutil function and maintaining it javascript always create a object on every function and that object is known us prototype .

so every function has a property named prototype which you can use to attach function so lets see how we can use it in our example

function Car(name,color){
    var car = Object.create(Car.prototype); // important change
    car.name = name;
    car.color = color;
    return car;
}
Car.prototype.start : function(){
        console.log('car is starting')
},
Car.prototype.stop : function(){
        console.log('car is stoping')
},
Car.prototype.move : function(){  
        console.log('car is moving')
}
Note: Prototype exits only on functions not on the object returned from that function

Ok So lets Review what we have done till now  in Car Function.

  var car = Object.create(Car.prototype); // important change

we are manually creating a new object with Object.create() function with Car.prototype to share some functions (like start stop and move) with different instances

return car;

and we are returning car instance which have created

so till now you might have guessed what we are doing Car is a class and we are creating different objects of that class right

var thar = Car("Thar","grey");
var swift = Car("Swift","white");

but we know that if we are creating an instance of class we use new  keyword right then what is the difference between with and without new keyword

new keyword

var thar = Car("Thar","grey");
var swift = Car("Swift","white");

so the difference is when you use new keyword you dont have to manually create the instance in the car function and return it let me show you

function Car(name,color){
   // var car = Object.create(Car.prototype); // dont have to do it 
    this.name = name;   // car will be replaced by this
    this.color = color;  //// car will be replaced by this
    // return car;
}
Car.prototype.start : function(){
        console.log('car is starting')
},
Car.prototype.stop : function(){
        console.log('car is stoping')
},
Car.prototype.move : function(){  
        console.log('car is moving')
}

and now if you want to create an object from car class

var thar = new Car("Thar","grey");
var swift = new Car("Swift","white");

and this will be the exact same as above and we have created a class and we know now what is prototype and how it works

again a sugar coating to the above class will be creating a class in the new way that is

class Car{
  constructor(name,color){
      this.name = name;
      this.color = color;
  }
    start (){
        console.log('car is starting')
    }

    stop (){
        console.log('car is stoping')
    }
    move (){   // the new function
        console.log('car is moving')
    }

}

var thar = new Car("Thar","grey");
var swift = new Car("Swift","white");


again just to verify it is doing all the stuff for us behind the scene which have done above you can see the prototype of Car by running

console.log(Car.prototype)

and you will see

Important object does not have a prototype it is on the function like in our case that or swift ware object s and they do not have a prototype Car which is the class or function behind the scenes has the prototype object

so now how do we get the prototype from an object .

In javascript we have a function on Object class that is getPrototypeOf which excepts the object and give us the prototype

let proto = Object.getPrototypeOf(thar);
console.log(proto)

Thanks a lot for reading this