- Array() find
- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- AND operator
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Array slice() method
- Arrays
- Async await
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Environment
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Prototype
- Random
- Reduce
- Regex
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- setTimeout() method
- Sleep() function
- Sort
- Splice
- String
- String concat()
- String indexOf()
- String slice() method
- Substring
- Switch statement
- Template literals
- Ternary operator
- throw Statement
- Title
- Type conversion
- void Operator
- While loop
JAVASCRIPT
JavaScript Prototype: Syntax, Usage, and Examples
The JavaScript prototype is a fundamental concept in the language’s object system. Every JavaScript object has a hidden property called [[Prototype]]
, which links it to another object. This prototype object allows properties and methods to be inherited, making JavaScript’s inheritance model flexible and powerful.
How to Use the JavaScript Prototype
At its core, the prototype in JavaScript provides a way to share behavior among objects. You can attach methods or properties to a constructor function’s .prototype
property so that all instances inherit them.
Here’s a simple example:
function Dog(name) {
this.name = name;
}
Dog.prototype.bark = function () {
return `${this.name} says woof!`;
};
const fido = new Dog("Fido");
console.log(fido.bark()); // Output: Fido says woof!
In this code, the method bark
isn’t defined directly on the fido
object. It’s defined on the prototype of Dog
, but fido
can still access it thanks to prototype chaining.
When to Use the JavaScript Prototype
1. To Enable Inheritance Between Objects
The prototype system allows one object to access properties and methods from another. This creates a shared structure that’s less memory-intensive than copying functions to every object.
For example, if you're creating many objects of the same type, using prototype JavaScript
syntax is more efficient than defining functions inside a constructor.
2. To Extend Built-in Object Behavior
You can add methods to native object prototypes like Array
, String
, or Object
to enhance their behavior. While this is powerful, it should be used cautiously to avoid naming conflicts.
Array.prototype.last = function () {
return this[this.length - 1];
};
const numbers = [1, 2, 3];
console.log(numbers.last()); // Output: 3
This extends all arrays to include a .last()
method via prototyping in JavaScript.
3. To Implement Shared Methods for Custom Types
Instead of repeating logic across instances, prototypes allow method reuse. If you're creating multiple users or shapes or database records, putting shared methods on the prototype helps with performance and organization.
Examples of Using the Prototype in JavaScript
1. Constructor Function and Prototype
function User(username) {
this.username = username;
}
User.prototype.sayHello = function () {
return `Hello, ${this.username}`;
};
const alice = new User("Alice");
console.log(alice.sayHello()); // Output: Hello, Alice
This is one of the most common uses of the JavaScript prototype — attaching methods to constructor functions for efficient inheritance.
2. Inheriting from Another Constructor
function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function () {
return `${this.name} is eating.`;
};
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;
Cat.prototype.meow = function () {
return `${this.name} says meow.`;
};
const whiskers = new Cat("Whiskers");
console.log(whiskers.eat()); // Output: Whiskers is eating.
console.log(whiskers.meow()); // Output: Whiskers says meow.
Here, Cat
inherits from Animal
using prototype chaining. This demonstrates inheritance through prototype-based design.
3. Checking Prototype Relationships
console.log(whiskers instanceof Cat); // true
console.log(whiskers instanceof Animal); // true
console.log(Object.getPrototypeOf(whiskers) === Cat.prototype); // true
These methods help determine the prototype structure of an object and are essential for debugging inheritance relationships.
Learn More About JavaScript Prototypes
What Is Prototype in JavaScript Exactly?
Each object in JavaScript has a hidden [[Prototype]]
internal slot. You can access or modify it using:
Object.getPrototypeOf(obj)
— returns the prototype ofobj
Object.setPrototypeOf(obj, prototype)
— sets a new prototype__proto__
— a legacy getter/setter that references the prototype (not recommended for production use)
When a property or method is accessed on an object, JavaScript looks for it directly on the object. If it doesn’t find it, it walks up the prototype chain until it finds the value or reaches null
.
This lookup mechanism is what gives JavaScript its prototypal inheritance.
Prototype vs. Class in JavaScript
Since ES6, JavaScript introduced the class
keyword, which provides a cleaner syntax over the older constructor function and prototype model. However, under the hood, the class system still uses prototypes.
class Person {
constructor(name) {
this.name = name;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
const bob = new Person("Bob");
console.log(bob.greet()); // Output: Hi, I'm Bob
If you inspect bob
, you’ll see greet()
lives on Person.prototype
, not directly on the instance. So even with class syntax, the prototype in JavaScript is still doing the work.
Prototype Chain
Here’s how the prototype chain works:
const obj = {};
console.log(obj.toString()); // inherited from Object.prototype
In this example, obj
has no toString()
method of its own, but it inherits one through the prototype chain.
The typical chain looks like this:
object → Object.prototype → null
For a class instance:
instance → Class.prototype → Object.prototype → null
Understanding this structure helps avoid confusion about where methods are coming from and how overrides work.
Prototyping in JavaScript for Performance
Using the prototype model is also memory-efficient. If you create 1000 objects using the same constructor, putting shared methods on the prototype means you only allocate memory for the function once.
function Car(model) {
this.model = model;
}
Car.prototype.drive = function () {
return `${this.model} is driving.`;
};
const c1 = new Car("Tesla");
const c2 = new Car("BMW");
console.log(c1.drive()); // Output: Tesla is driving.
console.log(c2.drive()); // Output: BMW is driving.
Here, both c1
and c2
share the same drive
function via the prototype, avoiding duplication.
Custom Object Creation with Object.create()
You can also use Object.create()
to set up prototypes directly:
const animal = {
speak() {
return "Animal sound";
},
};
const dog = Object.create(animal);
dog.bark = function () {
return "Woof";
};
console.log(dog.speak()); // Output: Animal sound
console.log(dog.bark()); // Output: Woof
This approach gives you full control over the prototype chain and is useful for lightweight object modeling without using classes or constructor functions.
Built-In Prototypes
In JavaScript, all built-in types come with their own prototypes:
Array.prototype
String.prototype
Function.prototype
Object.prototype
Date.prototype
RegExp.prototype
You can inspect or extend them:
console.log(Array.prototype); // All array methods live here
You can also (carefully) add to them:
String.prototype.shout = function () {
return this.toUpperCase() + "!";
};
console.log("hello".shout()); // Output: HELLO!
Be cautious with extending native prototypes, especially in shared codebases. You may conflict with other libraries or future features.
Best Practices for Working with Prototypes
- Prefer class syntax for clarity in modern code, especially in teams or open-source projects.
- Use prototypes to share methods across object instances to save memory and avoid duplication.
- Avoid modifying native prototypes unless you're absolutely sure what you're doing.
- Use
Object.create()
for simple inheritance when full class syntax feels too heavy. - Inspect the prototype chain with
Object.getPrototypeOf()
or Chrome DevTools to understand object relationships. - Don’t rely on
__proto__
. It's widely supported but considered deprecated.
The JavaScript prototype system is the backbone of inheritance in the language. Instead of relying on classes and traditional object-oriented inheritance, JavaScript uses prototypal chains where objects can inherit from other objects.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.