Chuck's Academy

Intermediate JavaScript

Prototype Manipulation and Inheritance

JavaScript is a prototype-based language, which allows objects to inherit properties and methods from other objects. In this chapter, we will explore the prototype system in JavaScript and how it is used to implement inheritance.

Prototype in JavaScriptPrototype in JavaScript

Prototypes in JavaScript

Each object in JavaScript has a prototype, which is another object from which it inherits properties and methods. This allows objects to share functionality without duplicating code.

javascript
"In this example, 'user' inherits the 'greet' method from the 'person' prototype, allowing 'user' to access this method without it being defined directly."

Constructor and prototype

Constructors are functions that allow creating multiple instances of an object with similar properties. Using the prototype property, we can define methods that will be shared among all instances.

javascript
"Here, 'Person' is a constructor that defines the property 'name' in each instance. By defining 'greet' on 'Person.prototype', the method is shared among all instances of 'Person'."

Inheritance in JavaScript

We can create a chain of prototypes to implement inheritance, allowing an object to inherit properties from another.

javascript
"In this example, 'Employee' inherits from 'Person' using 'call' and 'Object.create', allowing 'Employee' to access the methods of 'Person'."

Classes and Inheritance Syntax

With ES6, JavaScript introduced a clearer syntax for working with inheritance through the class keyword.

javascript
"Here, we use 'class' and 'extends' to create an 'Employee' class that inherits from 'Person'. This makes the code clearer and easier to understand."

Method Overriding

When a child class needs different behavior, it can override an inherited method.

javascript
"In this example, 'Employee' overrides the 'greet' method from 'Person', providing a different message."

instanceof and isPrototypeOf

JavaScript offers instanceof and isPrototypeOf to check inheritance relationships.

javascript
"We use 'instanceof' to check if 'alice' is an instance of 'Person', and 'isPrototypeOf' to see if the 'Person' prototype is in 'alice's prototype chain."

Conclusion

Prototype manipulation and inheritance in JavaScript are key concepts for building modular and reusable applications. Understanding how the prototype system works allows you to write more flexible code and leverage JavaScript's inheritance model.


Ask me anything