Menu
Posted At Thu, Oct 19, 2023 8:37 AM

JavaScript Prototypal Inheritance

Listen | 2 min read

Table of Contents

1. Introduction to Prototypal Inheritance
2. The Prototype Chain
3. Creating Objects with Constructors
4. Adding Methods to the Prototype
5. Inheriting Properties and Methods
6. Overriding Prototype Methods
7. Conclusion

1. Introduction to Prototypal Inheritance

JavaScript relies on a prototype-based model for inheritance. Unlike classical languages, where classes define object blueprints, JavaScript uses prototypes for object inheritance. This makes understanding prototypal inheritance crucial for JavaScript developers.

2. The Prototype Chain

Every JavaScript object has a prototype, which serves as a blueprint for that object. When you access a property or method on an object, JavaScript looks up the prototype chain to find it. If it doesn't find the property on the object itself, it continues searching up the chain.

3. Creating Objects with Constructors

You can create objects with constructors that define their structure. Constructors are regular functions but are named with capital letters by convention. For example:

function Person(name) {
  this.name = name;
}

const john = new Person('John');

4. Adding Methods to the Prototype

To share methods across objects efficiently, you can add them to the constructor's prototype. All instances created from the constructor will then inherit these methods:

Person.prototype.greet = function() {
  return 'Hello, my name is ' + this.name;
};

5. Inheriting Properties and Methods

Objects created with a constructor inherit properties and methods from the constructor's prototype. This allows for more memory-efficient object creation.

6. Overriding Prototype Methods

You can override inherited methods in a specific instance without affecting other instances or the prototype itself:

john.greet = function() {
  return 'Hey there!';
};

7. Conclusion

Prototypal inheritance is a fundamental concept in JavaScript. Understanding the prototype chain, constructors, and prototype methods will help you build efficient and maintainable code.

Next one is learning about JavaScript Object Prototype.

Click this link!
JavaScript Object Prototype

1410 1

Comments