Object Creation in Javascript

September 19, 2017

There are two ways to create object in Javascript

Method 1
Creating objects with object literals

In this method you can create properties and method in following way

let product={
    name:"Sprite",
    category:"Drink",
    price:10,
    getDiscount:function(){
        return this.price*5/100
    }
}

I have three properties name,category and price. You can see getDiscount() method too

With this object you can do following operations

To set the property of the object
product.name="Burger"
product.category="food"

You can get property of the object
console.log("Product Name "+product.name)

You can call the method
console.log("Discount is "+product.getDiscount())

Method 2

Using Constructor Function to create object

In Javascript you can use the constructor function to create objects. This is like class what you find in other programming language like Java,C# etc. If you need you can pass arguments too when you define the constructor function

I am using Product constructor function with one argument called name

function Product(name){
    this.name=name,
    this.category="food",
    this.price=10,
    this.getDiscount=function(){
      return this.price*5/100
    }
}

You can use new operator to create object
>p= new Product(“Burger")

To access the property of the object
>p.name
>Burger

To call the method of the object
>p.getDiscount()
>Discount is 0.5