JavaScript Constructor Functions and Prototypes Explained

Constructor Functions and Prototypes

1. Introduction

In traditional OOP languages like Java, classes serve as templates for objects. Before ES6, JavaScript lacked class definitions, instead using constructor functions to create objects.

2. Constructor Functions

Constructor functions initialize objects when used with the new keyword. Key characteristics:

  • Names should start with uppercase letters
  • Must be called with new to work properly

When new is used:

  1. Creates an empty object in memory
  2. Sets this to point to the new object
  3. Executes constructor code to add properties/methods
  4. Returns the new object

Example:

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.greet = function() {
        console.log('Hello');
    };
}

const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);

3. Prototype Objects

Each constructor has a prototype property that allows method sharing across instances:

Person.prototype.sing = function() {
    console.log('Singing');
};

person1.sing(); // All instances can access this

4. Protoytpe Chain

JavaScript uses a lookup chain for properties/methods:

  1. Checks the object itself
  2. Checks the prototype
  3. Continues up to Object.prototype
  4. Ends at null

5. Inheritance Patterns

Pre-ES6 inheritance can be implemented using:

function Student(name, age, grade) {
    Person.call(this, name, age); // Inherit properties
    this.grade = grade;
}

// Inherit methods
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

6. ES5 Array Methods

New array methods entroduced:

  • forEach(): Iterates through elements
  • filter(): Creates new array with matching elements
  • some(): Tests if any elements pass a test

Example:

const numbers = [1, 2, 3];
numbers.forEach(function(num) {
    console.log(num);
});

7. Object Methods

Key object utilities:

  • Object.keys(): Returns array of property names
  • Object.defineProperty(): Defines/modifies properties

Example:

const obj = {a: 1, b: 2};
Object.defineProperty(obj, 'c', {
    value: 3,
    writable: false
});

Tags: javascript Constructors Prototypes OOP ES5

Posted on Thu, 07 May 2026 06:47:30 +0000 by fr34k2oo4