DEV Community

Heru Hartanto
Heru Hartanto

Posted on

3 2

Object constructor in javascript

Object constructor is a blueprint of an object, it is a function that is used to create an object.

function Person(first,last,age){
    this.firstname= first;
    this.lastname = last,
    this.age = age;
}

const father = new Person('Jhon','Doe',24);
const mother = new Person('Jean','Doe',28);

Enter fullscreen mode Exit fullscreen mode

In those example, we call Person function two times, thereby it create two different instance of the functions, since we use new keyword, it create two different object that set into father and mother variable.

However we cannot add new properties or methods to an object constructor directly in the way we add properties or methods to an object.

    Person.nationality = "USA";
    const father = new Person('Jhon','Doe',24);
    father.nationality
    // undefined
Enter fullscreen mode Exit fullscreen mode

To add new properties or new methods to the object constructor, we can use prototype

    Person.prototype.nationality = "USA";
    father.nationality
    // USA
Enter fullscreen mode Exit fullscreen mode

Now every object created using the object constructor Person will have property nationality set to USA

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay