What does prototypal inheritance mean?

Experience Level: Medior
Tags: JavaScript

Answer

Prototypal inheritance is a fundamental concept in JavaScript that allows objects to inherit properties and methods from other objects. In JavaScript, every object has a prototype, which is a reference to another object. When a property or method is accessed on an object, JavaScript first checks if the object itself has that property or method. If it doesn't, JavaScript looks at the object's prototype and checks if it has the property or method. If the prototype doesn't have it, JavaScript looks at the prototype's prototype, and so on, until it reaches the end of the prototype chain.

One of the benefits of prototypal inheritance is that it allows for code reuse and abstraction. For example, you can create a "Person" object with properties like "name" and "age", and methods like "sayHello". You can then create a "Student" object that inherits from the "Person" object, and add properties like "grade" and methods like "study". The "Student" object will have access to all the properties and methods of the "Person" object, and can also add its own properties and methods.

Here's an example of how prototypal inheritance works in JavaScript:


// Create a "Person" object
var Person = function(name, age) {
  this.name = name;
  this.age = age;
};

// Add a "sayHello" method to the "Person" prototype
Person.prototype.sayHello = function() {
  console.log("Hello, my name is " + this.name);
};

// Create a "Student" object that inherits from "Person"
var Student = function(name, age, grade) {
  Person.call(this, name, age);
  this.grade = grade;
};

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

// Add a "study" method to the "Student" prototype
Student.prototype.study = function() {
  console.log(this.name + " is studying");
};

// Create a "john" object that is a "Student"
var john = new Student("John", 20, "A");

// Call the "sayHello" method on the "john" object
john.sayHello(); // Output: "Hello, my name is John"

// Call the "study" method on the "john" object
john.study(); // Output: "John is studying"

Related JavaScript job interview questions

Comments

Anonymous

Chat

Oh, the operator is not available. Leave us your comments. We will answer all your questions as soon as possible.

Comments

Anonymous
Καλησπέρα.
Anonymous
the infinteis -3/15 so 1triition / infinet
Anonymous
e
Anonymous
<a href="https://inspirum.pl "
Anonymous
[url]https://inspirum.pl[/url]
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e
LaceJaguar65
e