0
0
Javascriptprogramming~5 mins

Prototype inheritance in Javascript

Choose your learning style9 modes available
Introduction

Prototype inheritance lets one object use properties and actions from another object. It helps share features without copying them.

When you want many objects to share the same behavior without repeating code.
When creating objects that are variations of a base object, like different types of animals sharing common actions.
When you want to add new features to existing objects without changing them directly.
Syntax
Javascript
function Parent() {
  this.property = 'value';
}

Parent.prototype.method = function() {
  // code here
};

function Child() {
  Parent.call(this); // inherit properties
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

Parent.call(this) runs the parent function to copy properties to the child.

Object.create sets up the child to inherit methods from the parent's prototype.

Examples
This example shows a Dog inheriting from Animal. Dog changes the speak method.
Javascript
function Animal(name) {
  this.name = name;
}

Animal.prototype.speak = function() {
  console.log(this.name + ' makes a noise.');
};

function Dog(name) {
  Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.speak = function() {
  console.log(this.name + ' barks.');
};
Here, child inherits greet from parent using Object.create.
Javascript
const parent = { greet() { return 'Hello'; } };
const child = Object.create(parent);
console.log(child.greet());
Sample Program

This program shows a Student inheriting from Person. Student can use introduce from Person and also has its own study method.

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

Person.prototype.introduce = function() {
  console.log('Hi, I am ' + this.name);
};

function Student(name, subject) {
  Person.call(this, name);
  this.subject = subject;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

Student.prototype.study = function() {
  console.log(this.name + ' studies ' + this.subject);
};

const alice = new Student('Alice', 'Math');
alice.introduce();
alice.study();
OutputSuccess
Important Notes

Always reset the constructor property after setting the prototype to keep the right reference.

Prototype inheritance shares methods efficiently, so all objects use the same function in memory.

Summary

Prototype inheritance lets objects share properties and methods.

Use Object.create to link prototypes.

Call the parent function inside the child to copy properties.