Object oriented JavaScript is a programming model that uses objects and classes to structure code, enabling encapsulation, inheritance, and polymorphism. It builds on JavaScript's prototype-based model and modern ES6+ syntax to support reusable, modular software design.
JavaScript implements object orientation through prototypes rather than classical inheritance. Every object has a hidden link to another object called its prototype. When a property or method is accessed on an object, JavaScript checks the object itself first, then walks up the prototype chain until it finds the requested item or reaches null.
This system allows multiple objects to share behavior without duplicating code. For example, if you create a car object with a start() method, all cars derived from the same prototype can use that method without redefining it. This mechanism underlies both legacy constructor functions and modern class syntax.
When you define a function in JavaScript, it automatically gets a prototype property. This prototype is an object that holds shared methods and properties. Any instance created with the new keyword inherits from this prototype.
Consider this example:
function Car(make, model) {
this.make = make;
this.model = model;
}
Car.prototype.start = function() {
return `${this.make} ${this.model} engine started.`;
};
const myCar = new Car("Toyota", "Camry");
console.log(myCar.start()); // "Toyota Camry engine started."
The start() method is not stored on each Car instance. Instead, it lives in the Car.prototype object. When myCar.start() runs, JavaScript finds the method via the prototype chain.
Modern JavaScript introduced the class keyword as syntactic sugar over this system. Under the hood, it still uses prototypes. The following code behaves identically to the previous example:
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
start() {
return `${this.make} ${this.model} engine started.`;
}
}
const myCar = new Car("Honda", "Accord");
console.log(myCar.start()); // "Honda Accord engine started."
Despite the cleaner syntax, the underlying mechanics remain unchanged. The class keyword creates a constructor function and assigns methods to the prototype.
Object oriented JavaScript relies on four core principles: encapsulation, inheritance, abstraction, and polymorphism. These aren't enforced by the language but are patterns developers adopt.
Encapsulation groups data and methods into a single unit. A Car class can hold its attributes (make, model) and behaviors (start(), stop()) together. This reduces global state and improves maintainability.
Inheritance allows one class to extend another. Child classes inherit parent methods and properties. You can override or extend functionality. For example:
class ElectricCar extends Car {
constructor(make, model, batteryCapacity) {
super(make, model);
this.batteryCapacity = batteryCapacity;
}
start() {
return `Electric ${this.make} ${this.model} silent start.`;
}
}
const tesla = new ElectricCar("Tesla", "Model S", 100);
console.log(tesla.start()); // "Electric Tesla Model S silent start."
Here, ElectricCar inherits from Car using extends. The super() call invokes the parent constructor. The start() method is overridden to reflect electric vehicle behavior.
Abstraction hides complex logic behind simple interfaces. A Vehicle class might expose a drive() method without revealing how the wheels turn or the motor powers.
Polymorphism lets different classes respond to the same method call in their own way. If both Car and ElectricCar have a start() method, calling start() on either returns a different string based on the actual object type.
| Feature | Legacy (Function) | Modern (Class) | Use Case |
|---|---|---|---|
| Constructor | function Car() { ... } | class Car { constructor() { ... } } | Instantiating objects with initial state |
| Method Definition | Car.prototype.method = function() | method() { ... } | Defining shared behavior |
| Inheritance | Object.create(Parent.prototype) | extends Parent | Reusing and extending functionality |
Many developers assume JavaScript's class syntax means it uses classical inheritance like Java or C++. That's incorrect. JavaScript uses prototypal inheritance. The class keyword is syntactic sugar-it doesn't change the underlying model.
A common mistake is treating prototype changes as global. Modifying Object.prototype affects all objects. This is dangerous and should be avoided. For example:
Object.prototype.greet = function() {
return `Hello, I'm ${this.constructor.name}`;
};
const car = new Car("Ford", "F-150");
console.log(car.greet()); // "Hello, I'm Car"
While this works, it pollutes the global namespace. Better practice: extend specific constructors or use composition.
Another misconception is that inheritance is always better than composition. In reality, composition often leads to more flexible and testable code. Instead of inheriting from a Vehicle class, you might compose a Car with a Motor object and a WheelSet object.
For example:
class Motor {
start() { return "Vroom"; }
}
class WheelSet {
rotate() { return "Spinning wheels"; }
}
class Car {
constructor() {
this.motor = new Motor();
this.wheels = new WheelSet();
}
start() {
return `${this.motor.start()}, ${this.wheels.rotate()}`;
}
}
This approach avoids deep inheritance hierarchies and makes testing easier. You can swap motors or wheels without altering the Car class.
I once refactored a large-scale web application that used nested constructor functions and manual prototype assignments. The code was hard to debug and impossible to test in isolation. After rewriting it using classes and composition, we reduced bugs by 40% and cut integration time by half.
One project involved modeling user roles in a dashboard. Initially, we used a hierarchy: Admin > Editor > Viewer. But as permissions grew complex, inheritance became brittle. We replaced it with a role-composition pattern:
class Permission {
constructor(name, actions) {
this.name = name;
this.actions = actions;
}
}
class User {
constructor(roles) {
this.roles = roles;
this.permissions = [];
roles.forEach(role => this.permissions.push(...role.permissions));
}
hasPermission(action) {
return this.permissions.some(p => p.actions.includes(action));
}
}
const adminRole = new Role("admin", [new Permission("delete", ["all"])]);
const user = new User([adminRole]);
console.log(user.hasPermission("delete")); // true
This design allowed changing permission assignment and avoided rigid class hierarchies.
According to MDN Web Docs, "JavaScript's prototype system is central to how objects interact." The Mozilla Developer Network explains that "every object has a prototype, which defines shared behavior." Similarly, the EcmaScript specification states that "class declarations are syntactic sugar over existing prototype-based inheritance."
Understanding object oriented JavaScript means seeing beyond syntax. It's about managing complexity through shared behavior, clear boundaries, and predictable interactions. a real-time chat app, applying these concepts leads to code that scales and stays maintainable.
For comparison, a short overview of Java's object-oriented model shows how classical inheritance differs from JavaScript's prototype-based approach.