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
newto work properly
When new is used:
- Creates an empty object in memory
- Sets
thisto point to the new object - Executes constructor code to add properties/methods
- 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:
- Checks the object itself
- Checks the prototype
- Continues up to
Object.prototype - 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 elementsfilter(): Creates new array with matching elementssome(): 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 namesObject.defineProperty(): Defines/modifies properties
Example:
const obj = {a: 1, b: 2};
Object.defineProperty(obj, 'c', {
value: 3,
writable: false
});