DEV Community

Harini
Harini

Posted on

Constructor function in JavaScript

Constructor Function:

  • A constructor is used to initialize object properties with object-specific values.

- object properties -> data inside an object
(name, age, price, etc.)

- object-specific values -> values that are different for each object

  • A constructor is called automatically when an object is created using the new keyword.

Example

const myBook1 = new Book("Atomic Habits","James Clear",499,"Self Help")
        const myBook2 = new Book("Psychology of Money","Morgan Housel",399,"Finance")
        const myBook3 = new Book("Killers of the Flower Moon"," David Grann",370,"True Crime")
        const myBook4 = new Book("The Silent Patient","Alex Michaelides",399,"Psychological Thriller")

        function Book(name,author,price,genre){
            this.bookName = name,
            this.authorName = author,
            this.price = price,
            this.genre = genre;
        }
        console.log(myBook1.bookName);     //Atomic Habits
Enter fullscreen mode Exit fullscreen mode

Top comments (0)