Prototypes in JavaScript
JavaScript uses a prototypal inheritance model where objects can inherit properties and methods from other objects. Understanding prototypes is crucial for object-oriented programming in JavaScript.
Prototype Chain
// Basic prototype chain
const animal = {
eat: function() {
console.log('eating...');
}
};
const dog = Object.create(animal);
dog.bark = function() {
console.log('woof!');
};
// dog can access both bark() and eat()
dog.bark(); // 'woof!'
dog.eat(); // 'eating...'Constructor Functions
// Constructor function
function Person(name) {
this.name = name;
}
// Adding method to prototype
Person.prototype.sayHello = function() {
return `Hello, I'm ${this.name}`;
};
const john = new Person('John');
console.log(john.sayHello()); // "Hello, I'm John"
// Checking prototypes
console.log(john.__proto__ === Person.prototype); // true
console.log(Person.prototype.__proto__ === Object.prototype); // trueClass Syntax (ES6+)
// Modern class syntax (still uses prototypes under the hood)
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
constructor(name) {
super(name);
}
speak() {
console.log(`${this.name} barks`);
}
}
const rex = new Dog('Rex');
rex.speak(); // "Rex barks"Prototype Methods
// Object.create()
const proto = {
greet() {
return 'Hello!';
}
};
const obj = Object.create(proto);
console.log(obj.greet()); // 'Hello!'
// hasOwnProperty
console.log(obj.hasOwnProperty('greet')); // false
console.log(proto.hasOwnProperty('greet')); // true
// Object.getPrototypeOf()
console.log(Object.getPrototypeOf(obj) === proto); // true
// Setting prototype
const child = {};
Object.setPrototypeOf(child, proto);
console.log(child.greet()); // 'Hello!'Common Interview Follow-up Questions
- What's the difference between __proto__ and prototype?
- How does prototypal inheritance differ from classical inheritance?
- Why use prototypes instead of regular object properties?
- What are the performance implications of the prototype chain?
Best Practices
- Prefer class syntax for cleaner code
- Avoid modifying built-in prototypes
- Use Object.create() for explicit prototype chains
- Keep prototype chains short for better performance
- Use composition over inheritance when possible