Bird
Raised Fist0
Javascriptprogramming~5 mins

Constructor functions in Javascript

Choose your learning style10 modes available
Introduction

Constructor functions help you create many similar objects easily. They set up new objects with properties and values.

When you want to create many objects with the same structure, like many users or cars.
When you want to organize your code to make object creation clear and reusable.
When you want each object to have its own properties but share the same setup steps.
When you want to add methods to objects created from the same constructor.
When you want to keep your code clean and avoid repeating the same object setup.
Syntax
Javascript
function ConstructorName(parameter1, parameter2) {
  this.property1 = parameter1;
  this.property2 = parameter2;
  // more properties or methods
}

The function name usually starts with a capital letter to show it is a constructor.

Use the new keyword to create a new object from the constructor.

Examples
This constructor creates a Person with a name and age.
Javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
}
Creates two Person objects with different names and ages.
Javascript
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
This constructor adds a method honk to each Car object.
Javascript
function Car(make, model) {
  this.make = make;
  this.model = model;
  this.honk = function() {
    console.log('Beep beep!');
  };
}
Sample Program

This program creates two dogs with names and breeds. Each dog can bark, printing a message with its name.

Javascript
function Dog(name, breed) {
  this.name = name;
  this.breed = breed;
  this.bark = function() {
    console.log(this.name + ' says Woof!');
  };
}

const dog1 = new Dog('Buddy', 'Golden Retriever');
const dog2 = new Dog('Max', 'Beagle');

dog1.bark();
dog2.bark();
OutputSuccess
Important Notes

Always use new when calling a constructor function to create a new object.

Inside the constructor, this refers to the new object being created.

Methods defined inside the constructor are created for each object separately. To save memory, use prototypes for shared methods.

Summary

Constructor functions help create many similar objects easily.

Use new to make a new object from a constructor.

this inside the constructor means the new object being made.

Practice

(1/5)
1. What does the new keyword do when used with a constructor function in JavaScript?
easy
A. Creates a new object and sets this to that object inside the constructor
B. Calls the constructor function without creating a new object
C. Deletes the constructor function after running
D. Returns a string representation of the constructor

Solution

  1. Step 1: Understand the role of new

    The new keyword creates a fresh object and sets this inside the constructor to that object.
  2. Step 2: Effect on constructor function

    It allows the constructor to initialize properties on the new object and then returns it automatically.
  3. Final Answer:

    Creates a new object and sets this to that object inside the constructor -> Option A
  4. Quick Check:

    new creates object = A [OK]
Hint: Remember: new makes a new object and sets this [OK]
Common Mistakes:
  • Thinking new just calls the function without creating an object
  • Believing new returns a string
  • Confusing new with deleting functions
2. Which of the following is the correct syntax to define a constructor function named Car?
easy
A. function Car() { this.make = 'Toyota'; }
B. var Car = () => { this.make = 'Toyota'; }
C. class Car { make = 'Toyota'; }
D. function Car[] { this.make = 'Toyota'; }

Solution

  1. Step 1: Identify valid constructor function syntax

    A constructor function is a normal function with a capitalized name, like function Car() {}.
  2. Step 2: Check each option

    function Car() { this.make = 'Toyota'; } uses correct function syntax. var Car = () => { this.make = 'Toyota'; } uses arrow function which does not bind this properly. class Car { make = 'Toyota'; } is a class, not a constructor function. function Car[] { this.make = 'Toyota'; } has invalid syntax with square brackets.
  3. Final Answer:

    function Car() { this.make = 'Toyota'; } -> Option A
  4. Quick Check:

    Constructor function = normal function with capital name [OK]
Hint: Use normal function with capital name for constructor [OK]
Common Mistakes:
  • Using arrow functions as constructors
  • Trying to use class syntax instead of function
  • Writing invalid function syntax with brackets
3. What will be the output of this code?
function Person(name) {
  this.name = name;
}
const p = new Person('Alice');
console.log(p.name);
medium
A. undefined
B. Error
C. Alice
D. Person

Solution

  1. Step 1: Understand object creation with constructor

    The new Person('Alice') creates a new object and sets this.name to 'Alice'.
  2. Step 2: Access the property

    Logging p.name prints the value assigned, which is 'Alice'.
  3. Final Answer:

    Alice -> Option C
  4. Quick Check:

    Property set by constructor = 'Alice' [OK]
Hint: Remember: this.name sets property on new object [OK]
Common Mistakes:
  • Expecting undefined because of missing return
  • Confusing constructor name with property value
  • Thinking console.log prints function name
4. Find the error in this constructor function:
function Animal(type) {
  type = type;
  this.type = type;
}
const a = new Animal('Dog');
console.log(a.type);
medium
A. Missing new keyword when creating object
B. Cannot assign this.type inside constructor
C. Constructor function name should be lowercase
D. The assignment type = type; does nothing and is redundant

Solution

  1. Step 1: Analyze the assignment type = type;

    This line assigns the parameter type to itself, which does nothing and is unnecessary.
  2. Step 2: Check other parts

    The line this.type = type; correctly assigns the parameter to the object property. The new keyword is used correctly. Function name capitalization is fine.
  3. Final Answer:

    The assignment type = type; does nothing and is redundant -> Option D
  4. Quick Check:

    Redundant self-assignment = B [OK]
Hint: Check if variables are assigned to themselves unnecessarily [OK]
Common Mistakes:
  • Thinking type = type; sets object property
  • Forgetting to use new keyword
  • Believing constructor names must be lowercase
5. You want to create a constructor function Book that takes title and author as parameters and adds a method describe that returns a string like "Title by Author". Which code correctly does this?
hard
A. function Book(title, author) { this.title = title; this.author = author; } Book.describe = function() { return `${this.title} by ${this.author}`; };
B. function Book(title, author) { this.title = title; this.author = author; this.describe = function() { return `${this.title} by ${this.author}`; }; }
C. function Book(title, author) { this.title = title; this.author = author; describe() { return `${this.title} by ${this.author}`; } }
D. function Book(title, author) { this.title = title; this.author = author; this.describe = `${this.title} by ${this.author}`; }

Solution

  1. Step 1: Check method definition inside constructor

    function Book(title, author) { this.title = title; this.author = author; this.describe = function() { return `${this.title} by ${this.author}`; }; } correctly defines describe as a function property on this, so each object has its own method.
  2. Step 2: Analyze other options

    function Book(title, author) { this.title = title; this.author = author; } Book.describe = function() { return `${this.title} by ${this.author}`; }; adds describe to the constructor function itself, not instances. function Book(title, author) { this.title = title; this.author = author; describe() { return `${this.title} by ${this.author}`; } } has invalid syntax for method inside function. function Book(title, author) { this.title = title; this.author = author; this.describe = `${this.title} by ${this.author}`; } assigns a string, not a function, so describe is not callable.
  3. Final Answer:

    function Book(title, author) { this.title = title; this.author = author; this.describe = function() { return `${this.title} by ${this.author}`; }; } -> Option B
  4. Quick Check:

    Method as function property on this = A [OK]
Hint: Define methods as functions on this inside constructor [OK]
Common Mistakes:
  • Adding methods to constructor function instead of instances
  • Using invalid syntax for methods inside functions
  • Assigning method as string instead of function
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard