⚡
Prototypes and Prototypal Inheritance
Advanced
130 XP
55 min
Lesson Content
Prototypes and Prototypal Inheritance
JavaScript uses prototypal inheritance - objects inherit properties and methods from their prototype. Understanding prototypes is key to mastering JavaScript.
Prototype Chain
// Every object has a prototype
const obj = {};
console.log(obj.toString); // Inherited from Object.prototype
// Prototype chain: obj -> Object.prototype -> nullAdding to Prototype
// Add method to all arrays
Array.prototype.last = function() {
return this[this.length - 1];
};
[1, 2, 3].last(); // 3Object.create()
const animal = {
speak: function() {
return 'Some sound';
}
};
const dog = Object.create(animal);
dog.speak(); // 'Some sound'Constructor Functions
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return `Hello, I'm ${this.name}`;
};
const person = new Person('John');
person.greet(); // 'Hello, I'm John'Example Code
Work with prototypes and prototypal inheritance
// Constructor function
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
return `${this.name} makes a sound`;
};
// Create instance
const animal = new Animal('Dog');
console.log(animal.speak());
// Object.create example
const personProto = {
greet: function() {
return `Hello, I'm ${this.name}`;
}
};
const person = Object.create(personProto);
person.name = 'Alice';
console.log(person.greet());
// Prototype chain
console.log('Has toString:', 'toString' in person);
console.log('Own property:', person.hasOwnProperty('name'));Expected Output:
Dog makes a sound Hello, I'm Alice Has toString: true Own property: true
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code