JS Object Constructors

Object Constructors

JavaScript constructors are powerful tools for creating objects with similar properties and methods. Whether you use the traditional constructor function or the newer class syntax, understanding constructors is key to mastering JavaScript.

By using constructors, you make your code more organized, reusable, and scalable. So next time you need similar objects in JavaScript, consider using a constructor to save time and make your code easier to maintain

Creating a Constructor Function

In JavaScript, a constructor is just a regular function, but there are some rules and conventions we follow when creating them. Here’s an example of how to make one:

function Person(name, age) {
this.name = name; // ‘this’ refers to the new object being created
this.age = age;
this.greet = function() {
console.log(“Hello, my name is ” + this.name);
};
}

•  this Keyword: Inside a constructor function, this refers to the new object being created.
•  Naming Conventions: By convention, constructor functions should start with a capital letter (like Person) to distinguish them from regular functions.

Creating Objects Using the Constructor

Now that we have a constructor, we can use it to create new objects. To do this, we use the new keyword:

let person1 = new Person(“Amir”, 25);
let person2 = new Person(“Saad”, 20);

In this example, person1 and person2 are two new objects, each created using the Person constructor. They each have their name, age, and greet function.

 
When you call a new Person(“Amir”, 25), JavaScript does the following:

1.  It creates an empty object.
2.  It sets this inside the constructor to refer to this new object.
3.  It assigns the properties (name, age, greet) to the new object.
4.  It returns the new object (if you don’t explicitly return something else).

The Role of New Keyword

The new keyword is crucial when using constructors. Without it, this would not refer to a new object, and the properties and methods would not be assigned correctly. Without new, you’d simply be calling a normal function, and this would point to the global object (in a browser, that’s the window object)

Why Use Constructors?

Constructors are useful when you need to create many objects with similar properties and behaviors. For example: 

If you wanted to create multiple instances of a car, each with different models but the same properties like speed or engineType.

Implementing constructor object

Here’s an example of how to make one:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Object Constructor Example</title>
</head>
<body>
<script>
// Car constructor function
function Car(model, speed, engineType) {
this.model = model;
this.speed = speed;
this.engineType = engineType;
}
// Create instances of the Car object
const car1 = new Car(‘Sedan’, 120, ‘V6’);
const car2 = new Car(‘SUV’, 150, ‘V8’);
const car3 = new Car(‘Hatchback’, 100, ‘Electric’);
// Accessing properties of the created cars
console.log(car1.model); // “Sedan”
console.log(car2.speed); // 150
console.log(car3.engineType); // “Electric”
</script>
</body>
</html>

Code Explanation:

1. Car Constructor Function:

function Car(model, speed, engineType) {
this.model = model;
this.speed = speed;
this.engineType = engineType;
}

  Car: This is the constructor function. In JavaScript, a constructor function is used to create objects. When you call new Car(), it creates a new instance of the Car object.
•  this.model = model;: This assigns the model property of the new object to the value passed in when the object is created.
  this.speed = speed;: Similarly, this assigns the speed property.
  this.engineType = engineType;: This assigns the engineType property.

The this keyword refers to the current instance of the object being created (the new Car).

2. Creating Instances of the Car Object:

function Car(model, speed, engineType) {
this.model = model;
this.speed = speed;
this.engineType = engineType;
}

  These lines create three new instances of the Car constructor function:
•  car1 is a Sedan with a speed of 120 and a V6 engine.
  car2 is an SUV with a speed of 150 and a V8 engine.
  car3 is a Hatchback with a speed of 100 and an Electric engine.

Each call to new Car() creates a new object with the provided properties.

3. Accessing Properties and Logging to Console:

console.log(car1.model); // “Sedan”
console.log(car2.speed); // 150
console.log(car3.engineType); // “Electric”

  console.log(car1.model);: This logs the model property of car1, which is ‘Sedan’.
  console.log(car2.speed);: This logs the speed property of car2, which is 150.
  console.log(car3.engineType);: This logs the engineType property of car3, which is ‘Electric’.

These lines simply output the properties of each Car instance to the browser’s developer console.

Output

Accessing-properties

Implementing Another constructor object

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Object Constructor Example</title>
</head>
<body>
<script>
// Constructor function for creating Person objects
function Person(name, age) {
this.name = name; // ‘this’ refers to the new object being created
this.age = age;
this.greet = function() {
console.log(“Hello, my name is ” + this.name);
};
}
// Creating two Person objects
let person1 = new Person(“Amir”, 25);
let person2 = new Person(“Saad”, 20);
// Calling the greet method for both objects
person1.greet(); // This will log: “Hello, my name is Amir”
person2.greet(); // This will log: “Hello, my name is Saad”
</script>
</body>
</html>

Code Explanation:

1. The Constructor Function:

function Person(name, age) {
this.name = name; // ‘this’ refers to the new object being created
this.age = age;
this.greet = function() {
console.log(“Hello, my name is ” + this.name);
};
}

•  function Person(name, age): This is a constructor function. A constructor is a special kind of function used to create and initialize new objects. The function name Person follows the convention that constructor functions should start with a capital letter.
• this.name = name;: Inside the constructor, this refers to the newly created object (which will be assigned to person1, person2, etc. when you use new Person()).The line this.name = name; assigns the value passed to the name parameter to a property name of the new object.
• this.age = age;: Similarly, this.age = age; assigns the age parameter to the age property of the new object.
• this.greet = function() {…};: This defines a method greet() that will be available on all objects created using the Person constructor.The method simply logs a message to the console, using the this.name property of the object to introduce the person

2. Creating Instances of the Person Object:

let person1 = new Person(“Amir”, 25);
let person2 = new Person(“Saad”, 20);

•  let person1 = new Person(“Amir”, 25);: This line creates a new object person1 using the Person constructor. The new keyword:

       Creates a new empty object.
       Sets this inside the Person constructor to refer to that new object.
       Initializes the name property to “Amir” and the age property to 25.
       The greet() method is also assigned to person1.

•  let person2 = new Person(“Saad”, 20);: Similarly, this creates another object person2 with the name property set to “Saad” and the age property set to 20.

At this point, there are two objects:

  person1: An object with properties name: “Amir” and age: 25, and a method greet().
 person2: An object with properties name: “Saad” and age: 20, and a method greet().

3. Calling the greet() Method:

person1.greet(); // This will log: “Hello, my name is Amir”
person2.greet(); // This will log: “Hello, my name is Saad”

•  person1.greet(): This calls the greet() method of the person1 object. Inside the greet() method, this.name refers to person1.name, which is “Amir”. Therefore, the message “Hello, my name is Amir” is logged into the console.
•  person2.greet(): This calls the greet() method of the person2 object. Since this.name now refers to person2.name, which is “Saad”, the message “Hello, my name is Saad” is logged to the console.

Output

Practice Scenarios

1. Create an object named person with properties name, age, and city. Set appropriate values and log the entire object to the console.

Here’s an example program:

let person = {
name: “John”,
age: 25,
city: “New York”
};
console.log(person);

Output

2. Add a new property occupation to the person object from Example 1 and set its value to “Engineer”. Log the updated object to the console.

Here’s an example program:

let person = {
name: “John”,
age: 25,
city: “New York”
};
person.occupation = “Engineer”;
console.log(person);

Output

3. Create a function printInfo that takes a person object as a parameter and logs a message like “John is 25 years old and lives in New York.” using the object properties.

Here’s an example program:

let person = {
name: “John”,
age: 25,
city: “New York”
};
function printInfo(person) {
console.log(`${person.name} is ${person.age} years old and lives in ${person.city}.`);

Output

Function-printinfo

4. Create an object named car with properties make, model, and year. Write a function displayCarInfo that takes a car object as a parameter and logs a message like “The car is a Toyota Camry from 2020.”

Here’s an example program:

let car = {
make: “Toyota”,
model: “Camry”,
year: 2020
};
function displayCarInfo(car) {
console.log(`The car is a ${car.make} ${car.model} from ${car.year}.`);
}
displayCarInfo(car);

Output

Object-Names

5. Create an object named book with properties title, author, and pages. Write a function isLongBook that takes a book object as a parameter and returns true if the book has more than 300 pages, otherwise false.

Here’s an example program:

let book = {
title: “The Great Gatsby”,
author: “F. Scott Fitzgerald”,
pages: 218
};
function isLongBook(book) {
return book.pages > 300;
}
console.log(isLongBook(book)); // Output: false

Output

Course Video

Frequently Asked Questions

Still have a question?

Let's talk

An object constructor is a template for creating multiple objects with similar properties and methods using a constructor function. Learn more in our JavaScript object constructors free course video.

Define a constructor function, then use the new keyword to create an object.
Example:

function Person(name, age) { 

  this.name = name; 

  this.age = age; 

let person1 = new Person(“John”, 25); 

Check out examples in the JS object constructors with free video tutorial.

  • Object Literal: Creates a single object directly.
  • Object Constructor: Creates a blueprint for generating multiple objects with the same structure.
    Explore this in detail in the Free JavaScript object constructors tutorial for beginners.

Yes, you can add methods inside a constructor function.
Example:

function Person(name) { 

  this.name = name; 

  this.greet = function() { 

    console.log(“Hello, ” + this.name); 

  }; 

Learn how to implement this in the JavaScript object constructors with free tutorial.

The this keyword refers to the current object in the context of a method.
Example:

let person = { 

  name: “John”, 

  greet: function() { 

    console.log(`Hello, my name is ${this.name}`); 

  } 

}; 

Check out practical uses in the JavaScript object free course video.

Yes, ES6 introduces the class syntax, which simplifies the creation of objects.
Example:

class Person { 

  constructor(name, age) { 

    this.name = name; 

    this.age = age; 

  } 

Find out more in the JS object constructors with free video tutorial.

Use the instanceof operator.
Example:

console.log(person1 instanceof Person); // true 

Explore this concept in the Free JavaScript object constructors tutorial for beginners.

You can provide default values for properties if arguments are not passed.
Example:

function Car(make = “Toyota”) { 

  this.make = make; 

Watch detailed demonstrations in the JavaScript object constructors with free tutorial.

The prototype allows you to add shared methods or properties to all instances of an object created using the constructor. Learn more in the JavaScript object constructors free course video.

Yes, you can use constructors for inheritance by calling one constructor inside another using call() or super in ES6 classes.
Discover inheritance examples in the JS object constructors with free video tutorial.