Object-Oriented JavaScript: Prototypes, ES6 Classes, Inheritance & #Private Fields
Welcome to Phase 16: Object-Oriented JavaScript (OOP)! JavaScript uses a unique and powerful Prototypal Inheritance model. With the introduction of ES6 Classes, JavaScript provides a clean, syntactic standard for implementing the 4 core pillars of OOP: Encapsulation, Abstraction, Inheritance, and Polymorphism. In this comprehensive masterclass guide, you will master constructor functions, the prototype chain, ES6 class syntax, instance vs static methods, getters and setters, inheritance with extends and super, method overriding, private fields (#privateField), composition patterns, and construct 4 enterprise object-oriented applications.
JavaScript lo prati Object ki hidden link [[Prototype]] untundhi. Methods ni prototype meedha define chesthe, 1000 instances create chesina memory lo single method definition mathrame share avthundhi:
"use strict";
// 1. Constructor Function
function User(name, role) {
this.name = name;
this.role = role;
}
// 2. Attach shared method to Prototype
User.prototype.getRole = function() {
return this.name + " is a " + this.role;
};
const user1 = new User("Ravi", "Admin");
console.log(user1.getRole()); // "Ravi is a Admin"
console.log(Object.getPrototypeOf(user1) === User.prototype); // true
ES6 class syntax prototypal inheritance paina clean modern wrapper ga pani chesthundhi:
"use strict";
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Instance Method
displayDetails() {
console.log(this.name + " is " + this.age + " years old");
}
}
const student = new Student("Ravi", 20);
student.displayDetails(); // "Ravi is 20 years old"
staticMethods: Instance meedha kaakunda Class constructor meedha mathrame call avthayi (Utility helper methods e.g.Student.compare()).- Getters (
get) & Setters (set): Computed properties ni access cheyyadaniki mariyu data assignment appudu automatic validation run cheyyadaniki use avthayi.
"use strict";
class Temperature {
constructor(celsius) {
this._celsius = celsius;
}
// Getter
get fahrenheit() {
return (this._celsius * 9) / 5 + 32;
}
// Setter with validation
set celsius(val) {
if (val < -273.15) throw new Error("Temperature below absolute zero!");
this._celsius = val;
}
// Static Utility Method
static convertToKelvin(c) {
return c + 273.15;
}
}
const temp = new Temperature(25);
console.log("25ยฐC in Fahrenheit:", temp.fahrenheit); // 77
console.log("25ยฐC in Kelvin:", Temperature.convertToKelvin(25)); // 298.15
Child classes parent properties ni inherit chesukovadaniki extends mariyu super() vadathamu. Child class parent method ni override chesi specialized behavior chupinchadanni Polymorphism antaru:
"use strict";
// Parent Class
class Employee {
constructor(name, salary) {
this.name = name;
this.salary = salary;
}
calculateBonus() {
return this.salary * 0.10; // Standard 10% bonus
}
}
// Child Class extending Employee
class Manager extends Employee {
constructor(name, salary, teamSize) {
super(name, salary); // Call parent constructor
this.teamSize = teamSize;
}
// Polymorphism: Overriding parent method with specialized logic!
calculateBonus() {
return super.calculateBonus() + (this.teamSize * 500);
}
}
const dev = new Employee("Ravi", 60000);
const mgr = new Manager("Sneha", 100000, 8);
console.log(dev.name + " Bonus: Rs." + dev.calculateBonus()); // Rs. 6000
console.log(mgr.name + " Bonus: Rs." + mgr.calculateBonus()); // Rs. 14000 (10k + 4k team bonus)
JavaScript lo property name mundhu hash # pedithe adhi strictly Private avthundhi. Class bahata nunchi access cheyyadaniki try chesthe SyntaxError throw avthundhi!
"use strict";
class BankAccount {
#balance = 0; // True Private Field!
#pin;
constructor(owner, initialDeposit, pin) {
this.owner = owner;
this.#balance = initialDeposit;
this.#pin = pin;
}
deposit(amount) {
if (amount <= 0) throw new Error("Invalid deposit amount!");
this.#balance += amount;
return "Deposited Rs." + amount;
}
getBalance(enteredPin) {
if (enteredPin !== this.#pin) throw new Error("โ Unauthorized: Invalid PIN!");
return "Rs." + this.#balance;
}
}
const myAcc = new BankAccount("Ravi", 10000, 1234);
myAcc.deposit(5000);
console.log("Balance:", myAcc.getBalance(1234)); // Rs.15000
// console.log(myAcc.#balance); // โ SyntaxError: Private field '#balance' must be declared in an enclosing class!
Mastering Object-Oriented design patterns through 4 production-grade systems:
Project 1: Secure Bank Account Engine with Encapsulation
"use strict";
class SecureVault {
#funds = 0;
#auditLogs = [];
constructor(initialFunds) {
this.#funds = initialFunds;
this.#log("Account opened with Rs." + initialFunds);
}
#log(action) {
this.#auditLogs.push({ action, timestamp: new Date().toISOString() });
}
withdraw(amount) {
if (amount > this.#funds) return "โ Insufficient funds!";
this.#funds -= amount;
this.#log("Withdrew Rs." + amount);
return "โ
Withdrew Rs." + amount + " | Remaining: Rs." + this.#funds;
}
getAuditHistory() {
return [...this.#auditLogs]; // Return clone to prevent mutation
}
}
const vault = new SecureVault(50000);
console.log(vault.withdraw(15000));
console.log("Audit Logs Count:", vault.getAuditHistory().length);
Project 2: E-Commerce Product Hierarchy (Inheritance & Polymorphism)
"use strict";
class Product {
constructor(id, title, basePrice) {
this.id = id;
this.title = title;
this.basePrice = basePrice;
}
getFinalPrice() {
return this.basePrice; // Standard product has no discount
}
}
class DigitalProduct extends Product {
constructor(id, title, basePrice, downloadLink) {
super(id, title, basePrice);
this.downloadLink = downloadLink;
}
getFinalPrice() {
return this.basePrice * 0.90; // 10% off for instant digital downloads!
}
}
const book = new Product(1, "Clean Code Physical Book", 1000);
const ebook = new DigitalProduct(2, "Clean Code PDF", 1000, "https://download.io/pdf");
console.log(book.title + ": Rs." + book.getFinalPrice()); // Rs.1000
console.log(ebook.title + ": Rs." + ebook.getFinalPrice()); // Rs.900
Project 3: Vehicle Fleet Simulator (Polymorphic Engine)
"use strict";
class Vehicle {
constructor(brand) { this.brand = brand; }
startEngine() { return this.brand + " engine started (Standard Gas)."; }
}
class ElectricVehicle extends Vehicle {
startEngine() { return this.brand + " silently powered ON (Dual Motors Electric)."; }
}
const fleet = [new Vehicle("Toyota Corolla"), new ElectricVehicle("Tesla Model 3")];
fleet.forEach(v => console.log(v.startEngine()));
Project 4: User Permission Engine (Composition over Inheritance)
"use strict";
// Modular feature behaviors
const canRead = state => ({
read: () => console.log(state.name + " is reading article.")
});
const canWrite = state => ({
write: () => console.log(state.name + " published a new article.")
});
// Factory function composing features
function createAdminUser(name) {
const user = { name };
return Object.assign(user, canRead(user), canWrite(user));
}
const admin = createAdminUser("Ravi");
admin.read();
admin.write();
Run this ES6 Student class instance in our live Node.js / JavaScript compiler:
"use strict";
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
displayDetails() {
console.log(this.name + " is " + this.age + " years old");
}
}
const student = new Student("Ravi", 20);
student.displayDetails();