Prototype Basics
Every JavaScript object has an internal link to another object called its prototype. This prototype object can have its own prototype, forming a chain. This is how JavaScript implements inheritance.
The Prototype Property
function Person(name) {
this.name = name;
}
// Add method to prototype
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
const alice = new Person('Alice');
const bob = new Person('Bob');
console.log(alice.greet()); // 'Hello, I'm Alice'
console.log(bob.greet()); // 'Hello, I'm Bob'
// They share the same method
console.log(alice.greet === bob.greet); // true
How new Works
// When you call new Person('Alice'):
// 1. A new empty object is created: {}
// 2. The object's [[Prototype]] is set to Person.prototype
// 3. The constructor is called with 'this' bound to the new object
// 4. The new object is returned
function Person(name) {
this.name = name; // Step 3
}
const alice = new Person('Alice');
// Steps 1, 2, 4 happen implicitly
Checking Prototypes
const alice = new Person('Alice');
// Check if object has property directly
console.log('name' in alice); // true
console.log(alice.hasOwnProperty('name')); // true
// Check prototype
console.log('greet' in alice); // true (from prototype)
console.log(alice.hasOwnProperty('greet')); // false
// Get prototype
console.log(Object.getPrototypeOf(alice) === Person.prototype); // true
Prototype Methods
You can add methods and properties to prototypes to share them across instances.
Adding Methods
function Car(make, model) {
this.make = make;
this.model = model;
}
// Add method to prototype
Car.prototype.start = function() {
return `${this.make} ${this.model} started`;
};
// Add property to prototype
Car.prototype.wheels = 4;
const myCar = new Car('Toyota', 'Camry');
console.log(myCar.start()); // 'Toyota Camry started'
console.log(myCar.wheels); // 4
Modifying Built-in Prototypes
// Add useful methods to Array prototype
Array.prototype.last = function() {
return this[this.length - 1];
};
Array.prototype.isEmpty = function() {
return this.length === 0;
};
const arr = [1, 2, 3];
console.log(arr.last()); // 3
console.log([].isEmpty()); // true
// WARNING: Modifying built-ins is generally discouraged
// It can cause conflicts with future JS features
Prototype vs Instance Properties
function Dog(name) {
this.name = name; // Instance property (unique to each)
}
Dog.prototype.species = 'Canine'; // Prototype property (shared)
const rex = new Dog('Rex');
const fido = new Dog('Fido');
// Instance properties are unique
console.log(rex.name); // 'Rex'
console.log(fido.name); // 'Fido'
// Prototype properties are shared
console.log(rex.species); // 'Canine'
console.log(fido.species); // 'Canine'
// Modifying prototype affects all instances
Dog.prototype.species = 'Dog';
console.log(rex.species); // 'Dog'
console.log(fido.species); // 'Dog'
Object.create
Object.create() creates a new object with a specified prototype.
Basic Usage
const personProto = {
greet() {
return `Hello, I'm ${this.name}`;
},
toString() {
return `Person: ${this.name}`;
}
};
const alice = Object.create(personProto);
alice.name = 'Alice';
console.log(alice.greet()); // 'Hello, I'm Alice'
Creating with Properties
const carProto = {
start() {
return `${this.make} ${this.model} started`;
}
};
const myCar = Object.create(carProto, {
make: { value: 'Toyota', writable: true, enumerable: true },
model: { value: 'Camry', writable: true, enumerable: true },
year: { value: 2024, writable: false } // Read-only
});
console.log(myCar.start()); // 'Toyota Camry started'
console.log(myCar.year); // 2024
Inheritance with Object.create
const animal = {
eat() {
return 'Eating...';
},
sleep() {
return 'Sleeping...';
}
};
const dog = Object.create(animal);
dog.bark = function() {
return 'Woof!';
};
const rex = Object.create(dog);
rex.name = 'Rex';
console.log(rex.bark()); // 'Woof!'
console.log(rex.eat()); // 'Eating...'
console.log(rex.sleep()); // 'Sleeping...'
Prototype Chain with Object.create
const base = { type: 'base' };
const child = Object.create(base);
child.name = 'child';
const grandchild = Object.create(child);
console.log(grandchild.type); // 'base' (from base)
console.log(grandchild.name); // 'child' (from child)
// Check chain
console.log(Object.getPrototypeOf(child) === base); // true
console.log(Object.getPrototypeOf(grandchild) === child); // true
Practice Problems
Create a reusable React component implementing Prototype. Include proper state management and accessibility.
Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where neededWrite unit and integration tests for Prototype using React Testing Library.
Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility testsOptimize Prototype for performance. Consider memoization, code splitting, and bundle size.
Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysisQuiz
1. What is a prototype in JavaScript?
2. How do you add a method to all instances of a constructor?
3. What does Object.create() do?
4. Why share methods via prototype instead of in the constructor?
Flashcards
Question
What is a prototype?
Click to reveal answer
Answer
An internal link from an object to another object, forming a chain for inheritance and method sharing.
Question
How to add shared methods?
Click to reveal answer
Answer
Add them to the constructor's prototype: Constructor.prototype.method = function() {}
Question
What is Object.create()?
Click to reveal answer
Answer
Creates a new object with the specified prototype object as its [[Prototype]].
Question
Why use prototype methods?
Click to reveal answer
Answer
Memory efficiency - all instances share the same method instead of each having its own copy.
Question
What is Prototype?
Click to reveal answer
Answer
Prototype is a key concept in frontend development.
Revision Notes
Key Takeaways
- 1.Every JavaScript object has a prototype
- 2.Prototype methods are shared across instances
- 3.Object.create() creates objects with a specific prototype
- 4.Prototypes enable inheritance in JavaScript
- 5.Use prototypes for memory-efficient method sharing
Interview Tips
- •Explain how prototypes enable inheritance
- •Show the difference between own and prototype properties
- •Demonstrate Object.create() for inheritance
- •Discuss why prototype methods are more memory efficient
Cheat Sheet
Prototype Cheat Sheet
What is it?
Internal link from object to another object for inheritance.
Constructor + Prototype
function Person(name) {
this.name = name; // Instance property
}
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
Object.create()
const obj = Object.create(proto, {
prop: { value: 'value' }
});
Key Points
- Every object has a prototype
- Methods on prototype are shared
- 'in' checks own + prototype
- hasOwnProperty() checks own only