Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Constructor functions are templates for creating multiple objects with the same properties and methods. Like a cookie cutter - define once, use many times!
function Person(name, age) {
this.name = name; // Property
this.age = age; // Property
this.greet = function() { // Method
console.log('Hi, I am ' + this.name);
};
}
// Create instances with 'new'
const person1 = new Person('Alice', 25);
const person2 = new Person('Bob', 30);Creating a Person constructor
Creates a new empty object: {}
Points this to the new object
Runs the function, adding properties to this
Automatically returns the new object (no return needed!)
Behind the scenes magic
function User(username, email) {
this.username = username;
this.email = email;
this.isActive = true;
this.login = function() {
console.log(`${this.username} logged in`);
};
}function Product(name, price) {
this.name = name;
this.price = price;
this.discount = function(percent) {
return this.price * (1 - percent / 100);
};
}function BankAccount(owner, balance) {
this.owner = owner;
this.balance = balance;
this.deposit = function(amount) {
this.balance += amount;
};
this.withdraw = function(amount) {
if (amount <= this.balance) {
this.balance -= amount;
}
};
}Practical applications
Instead of creating a new function for each instance, add methods to the prototype so all instances share the same function!
function Person(name) {
this.name = name;
// New function for EACH instance
this.greet = function() {
console.log('Hi ' + this.name);
};
}
// 100 instances = 100 copies of greet()function Person(name) {
this.name = name;
}
// ONE function shared by ALL instances
Person.prototype.greet = function() {
console.log('Hi ' + this.name);
};
// 100 instances = 1 copy of greet()Efficient method sharing
Use instanceof to check if an object was created by a specific constructor
function Person(name) {
this.name = name;
}
const alice = new Person('Alice');
console.log(alice instanceof Person); // true
console.log(alice instanceof Object); // true (all objects)
console.log(alice instanceof Array); // falseChecking object types
// 1. Define constructor (capital first letter)
function MyConstructor(param1, param2) {
this.property1 = param1;
this.property2 = param2;
}
// 2. Add methods to prototype
MyConstructor.prototype.method1 = function() {
// use this.property1, this.property2
};
// 3. Create instances with 'new'
const instance = new MyConstructor(value1, value2);