Menu
Coddy logo textTech

Constructor Functions

Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 4 of 56.

Constructor functions are special functions in JavaScript that allow you to create multiple objects with the same structure and behavior.

Define a constructor function for a Person:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    return "Hello, my name is " + this.name;
  };
}

Create a new Person object using the constructor:

const john = new Person("John", 30);
const tyler = new Person("Tyler", 35);

After executing the above code, john is an object with properties:

// john object contains:
{
  name: "John",
  age: 30,
  greet: function() { return "Hello, my name is John"; }
}

Access properties and call methods:

console.log(john.name); // Outputs: John
console.log(john.greet()); // Outputs: Hello, my name is John
challenge icon

Challenge

  1. Create a constructor function named Book that takes three arguments:
  • title (String)
  • author (String)
  • pages (Number)

The function should set these as properties on the object created. 

    2. Add a method called getSummary that returns a string with some information about the book: this.title + " was written by " + this.author + " and has " + this.pages + " pages";

Cheat sheet

Constructor functions create multiple objects with the same structure. Use the new keyword to create instances:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    return "Hello, my name is " + this.name;
  };
}

const john = new Person("John", 30);
console.log(john.name); // Outputs: John
console.log(john.greet()); // Outputs: Hello, my name is John

Try it yourself

// TODO: Create a constructor function named Book that takes three arguments (title, author, pages)


// TODO: Set these as properties on the object created


// TODO: Add a method called getSummary that returns a string with some information about the book.
// For example: Harry Potter was written by Rowling and has 500 pages


// Don't modify the code below
const inputTitle = inp[0];          // First line: book title
const inputAuthor = inp[1];         // Second line: author  
const inputPages = parseInt(inp[2]);// Third line: number of pages

const book = new Book(inputTitle, inputAuthor, inputPages);
console.log(book.getSummary());
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming