Object-Oriented Programming (OOP) in JavaScript
🎯 Introduction
This article explains JavaScript's object model, constructors and new, prototypes and prototype chains, property lookup, and several approaches to inheritance. These concepts provide a solid foundation for object-oriented frontend development and help you write better-structured, more efficient code.
🔍 What Is JavaScript's Object Model?
JavaScript is an object-based language, often described informally as treating “everything as an object.” Even primitive values such as numbers and strings can be used with object-like operations.
Primitive Values vs. Reference Values
This distinction is essential for beginners:
- Primitive types include
Number,String,Boolean,null,undefined, andSymbol(introduced in ES6).
Variables holding primitives contain values; assignment copies the value itself. - Reference types include objects, arrays, and functions (
Object,Array, andFunction).
Variables holding objects contain references. Assignment copies the reference, so both variables refer to the same object.
An everyday analogy:
A primitive value is like a package containing an item: copying it gives you a separate copy of the item. An object reference is like a house key: copying the key gives you access to the same house.
⚙️ Constructors and How new Works
Defining a Constructor
A constructor can be an ordinary function. By convention, its name starts with a capital letter to indicate that it creates objects.
function Person(name, age) {
this.name = name;
this.age = age;
this.sayHello = function () {
console.log('Hello, my name is ' + this.name);
};
}
The Four Steps of new
When you write new Person('Tom', 20), the JavaScript engine performs four steps:
- Create a new, empty object.
- Set its internal
[[Prototype]]to the constructor's.prototypeobject. - Call the constructor with
thisset to the new object and execute its body. - Return the new object unless the constructor explicitly returns an object.
A Simplified Implementation of new
Here is a simple simulation of new:
function myNew(fn, ...args) {
const obj = {};
Object.setPrototypeOf(obj, fn.prototype);
const result = fn.apply(obj, args);
return typeof result === 'object' && result !== null ? result : obj;
}
new helps explain how constructors create objects and connect the prototype chain.🧩 Prototypes and the .prototype Property
Why Do Functions Have .prototype?
Functions intended for use as constructors have a special .prototype property. For ordinary constructor functions, it initially holds an object with a constructor property referring back to the function.
When the constructor creates an instance, the instance's __proto__ accessor exposes its internal prototype, which refers to this .prototype object.
Instances and Prototypes: proto vs. .prototype
- An instance's
__proto__exposes the object referenced by its constructor's.prototype. - A constructor's
.prototypeproperty refers to the prototype object.
This connection acts as a bridge: instances access the constructor's prototype through __proto__, allowing methods defined there to be shared.
const p = new Person('Jack', 25);
console.log(p.__proto__ === Person.prototype); // true
Constructor, Prototype Object, and Instance
Person (constructor)
|
| .prototype
↓
Person.prototype (prototype object) --- (prototype chain) ---> Object.prototype --- null
p (instance)
|__ __proto__ --> Person.prototype
🌲 Prototype Chains and Property Lookup
What Is a Prototype Chain?
An instance's prototype links to its constructor's .prototype object. That object links to its own prototype, continuing to Object.prototype and finally null. These links form the prototype chain.
Looking Up Properties and Methods
When you access a property or method, JavaScript checks the object's own properties first. If it finds no match, it follows the prototype chain exposed by __proto__, stopping when it reaches null.
For example:
console.log(p.sayHello); // First checks p for its own sayHello property
// If p has no such property, checks Person.prototype next
How Object.create Works
Object.create(proto) creates an object whose prototype, exposed by __proto__, is proto. It is a concise way to establish an inheritance chain.
const obj = Object.create(Person.prototype);
Object.create lets you create prototype-based inheritance relationships directly, without calling a constructor.🌿 Implementing Inheritance
Prototype Chain Inheritance
Set the child constructor's prototype to an instance of the parent constructor.
function Parent() {
this.name = 'parent';
}
Parent.prototype.say = function () {
console.log('hello');
};
function Child() {}
Child.prototype = new Parent();
const c = new Child();
c.say(); // hello
The drawback is that all child instances share reference-valued properties stored on the parent instance.
Constructor Borrowing with call
Call the parent constructor inside the child constructor with the child's this. This avoids sharing reference-valued instance properties.
function Child() {
Parent.call(this);
}
The drawback is that this only initializes properties and methods defined in the parent constructor; it does not inherit methods from the parent's prototype.
Combination Inheritance
Combine both approaches to inherit instance properties and prototype methods.
function Child(name) {
Parent.call(this);
this.name = name;
}
Child.prototype = new Parent(); // Child.prototype.constructor now refers to Parent
Child.prototype.constructor = Child; // Restore the constructor reference to Child
class and extends as Syntactic Sugar
ES6 introduced class syntax to make inheritance more concise:
class Parent {
constructor() {
this.name = 'parent';
}
say() {
console.log('hello');
}
}
class Child extends Parent {
constructor() {
super();
}
}
The underlying model still uses prototypes and constructors. The syntax is clearer and resembles traditional object-oriented languages.
❓ Knowledge Check
Q1: How does a constructor differ from a regular function?
Constructors conventionally have capitalized names and create objects when called with new. Regular functions do not follow that convention or purpose.
Q2: Why use prototype chains for inheritance? They allow instances to share parent methods, saving memory and supporting flexible inheritance relationships.
Q3: How does Object.create differ from constructor borrowing?Object.create explicitly sets an object's prototype, giving you direct control over inheritance. Constructor borrowing primarily initializes instance properties.
🧪 Exercises
- Use a constructor and
newto create aCarobject withbrandandspeedproperties and arunmethod that logs its driving status.
function Car(brand, speed) {
// Your code here
}
const myCar = new Car('Toyota', 80);
myCar.run(); // Prints: Toyota is running at 80 km/h
- Implement prototype chain inheritance between
AnimalandDog. GiveAnimalaneatmethod, and letDoginherit it and add abarkmethod.
function Animal() {
// Your code here
}
Animal.prototype.eat = function () {
console.log('Eating food');
};
function Dog() {
// Your code here
}
// Inherit from Animal's prototype
Dog.prototype.bark = function () {
console.log('Woof!');
};
const dog = new Dog();
dog.eat();
dog.bark();
🎉 You now understand JavaScript's object model, constructors and new, prototype chains, property lookup, and inheritance! Use these concepts to write clearer object-oriented code.
Shallow and Deep Copies
Learn how shallow and deep copies work, how to implement them, and how to avoid common pitfalls with object references.
Introduction to Functional Programming
Learn functional programming fundamentals, including pure functions, side effects, higher-order functions, function composition, and currying.
