DEV Community

Cover image for JavaScript Object Constructor
karthika jasinska
karthika jasinska

Posted on

JavaScript Object Constructor

Object Constructor Functions
Sometimes we need to create many objects of the same type.

To create an object type we use an object constructor function.

It is considered good practice to name constructor functions with an upper-case first letter.

Example:

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
console.log(myFather);
Output:
Person {firstName: 'John', lastName: 'Doe', age: 50, eyeColor: 'blue'}
Enter fullscreen mode Exit fullscreen mode

Adding a Property to a Constructor:
To add a new property, you must add it to the constructor function prototype:

Person.prototype.nationality = "Tamil";
console.log(myFather.nationality);
output:
Tamil
Enter fullscreen mode Exit fullscreen mode

Adding a Method to an Object
Adding a method to a created object is easy,The new method will be added to myMother. Not to any other Person Objects

// Constructor function for Person Objects
function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

// Create 2 Person objects
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

// Add a Name Method
myMother.changeName = function (name) {
  this.lastName = name;
}

// Change Name
myMother.changeName("Deo");
console.log(myMother.lastName)

Output:
Deo
Enter fullscreen mode Exit fullscreen mode

Top comments (0)