DEV Community

Kavin Loyola S
Kavin Loyola S

Posted on

Constructor Function

Constructor

It automatically called when object is created, and it name should be starts with uppercase letter. In constructor, this refers to current object. it initializing object specific values.

how to create ?

To define a constructor function, we use the function keyword followed by the function name and parameters. Inside the function, we use the this keyword to assign properties and methods to the object being created. For example,


function laptop (price,brand,storage) {
    this.price=price;
    this.brand=brand;
    this.storage=storage;
}
laptop.price=40000;
laptop.brand="acer";
laptop.storage=512;
console.log(laptop.price);

o/p - 40000

Enter fullscreen mode Exit fullscreen mode

Adding methods

this.device = function(){
    return 'PC';
}
const buy = new Laptop;
console.log(buy.device());

o/p - PC

Enter fullscreen mode Exit fullscreen mode

Top comments (0)