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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up