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

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay