Exploring the Concept of Class Inheritance in Javascript

I've been thinking about how to implement Class Inheritance in JavaScript. Since JavaScript doesn't have classes like other languages, we typically use functions to create objects and handle inheritance through Prototype objects.

For instance, how would you translate this structure into JavaScript:

public class Mankind {
    public string name;
    public string lastname;
}

public class Person: Mankind {
    public void Run(string fromWhat) {
        //write the run logic
    }
}

What is the JavaScript equivalent of this code snippet?

Edit:

I also came across a link where Douglas Crockford discusses various inheritance models similar to classical inheritance in JavaScript: CMS and Classical Inheritance in JavaScript.

Hopefully, this information will be useful to others as well.

Answer №1

There are numerous approaches to incorporating inheritance and behavior reuse in JavaScript. One method that aligns closely with traditional class-based OOP is pseudo-classical inheritance:

function Mankind (name, lastname) {
  this.name = name;
  this.lastname = lastname;
}

function Person (name, lastname) {
  this.name = name;
  this.lastname = lastname;

  this.run = function() {
    // run logic
  };
}
Person.prototype = new Mankind();
Person.prototype.walk = function () {
  // walk logic
};

The key distinction between the run and walk methods is that the former is present on every instance of Person, while the latter, walk, exists solely on Person.prototype and is accessed through the prototype chain.

This pattern exhibits some code duplication, particularly in initializing fields within the inherited constructor. An alternative approach that mitigates this issue is Constructor Function application:

function Mankind (name, lastname) {
  this.name = name;
  this.lastname = lastname;
}

function Person (name, lastname) {
  Mankind.apply(this, arguments);
  this.run = function() {
    // run logic
  };
}

For more information:

  • How to inherit from a class in JavaScript (various examples)
  • Inheritance Patterns in JavaScript (article)
  • Classical Inheritance in JavaScript (article)

Answer №2

Revised for ES 6:

class Humanity {
    constructor (surname, givenName) {
      this.surname = surname;
      this.givenName = givenName;
    }
}

class Individual extends Humanity {
    move (fromWhere) {
        //implement the move method
    }
}

Answer №3

Take a look at this amazing resource for mooTools!

Answer №4

(function(){
function Humanity() {
    this.person = "joe";
}
function Individual(){
    this.Run = function(fromWhere){
        alert(this.person + ' runs from ' + fromWhere + '!');
    }
}
Individual.prototype = new Humanity;

var individual = new Individual;
individual.Run('bear');
})()

Instead of relying on static class-type definitions, JavaScript utilizes functions to dynamically construct data structure prototypes. This approach allows for building a structure as needed, based on gathered context. The dynamic nature of the prototype chain is a significant advancement that I am still trying to fully grasp.

For a clearer understanding, observe the following source code:

(function(){
// Example of prototype chaining
function part1(){this.foo = "foo"}
function part2(){this.bar = "bar"}
function part3(){this.bat = "bat"}
part2.prototype = new part1();
part3.prototype = new part2();
var x = new part1;
var y = new part2;
var z = new part3;
// Inherited state
var memberList = [
x.foo, // "foo"
x.bar, // undefined
x.bat, // undefined
y.foo, // "foo"
y.bar, // "bar"
y.bat, // undefined
z.foo, // "foo"
z.bar, // "bar"
z.bat // "bat"
];
// Chained prototypes
var instanceList = [
x instanceof part1, // true
x instanceof part2, // false
x instanceof part3, // false
y instanceof part1, // true
y instanceof part2, // true
y instanceof part3, // false
z instanceof part1, // true
z instanceof part2, // true
z instanceof part3 // true
];

// Attempt to break the chain
function part4(){this.fu = "fu"}
part2.prototype = new part4;

// State remains consistent
var memberList2 = [
x.foo, // "foo"
x.bar, // undefined
x.bat, // undefined
y.foo, // "foo"
y.bar, // "bar"
y.bat, // undefined
z.foo, // "foo"
z.bar, // "bar"
z.bat // "bat"
];
// Chain remains unbroken, but link is removed 
var instanceList2 = [
x instanceof part1, // true
x instanceof part2, // false
x instanceof part3, // false
y instanceof part1, // true
y instanceof part2, // false
y instanceof part3, // false
z instanceof part1, // true
z instanceof part2, // false
z instanceof part3 // true
];
// No new link is added
var instanceList3 = [
x instanceof part4, // false
y instanceof part4, // false
z instanceof part4 // false
];
debugger    
})()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on transitioning from a WebGL renderer to a canvas renderer in three.js

My goal is to display a scene using either a WebGL renderer or a canvas renderer in three.js (version 69). This is the code I am using: <!DOCTYPE html> <html> <head> <script src="./libs/three.js"></script> <scri ...

What is the best way to apply a conditional binding with v-model in Vue.js?

When working with JavaScript, you can utilize object spreading to include optional values like shown below: const payload = { name: "Joseph", ...(isMember && { credential: true }) }; In React, passing props optionally in JSX is as simple as this: &l ...

Vue-Routes is experiencing issues due to a template within one of the routes referencing the same ID

I encountered an issue while developing a Vue application with Vue-routes. One of the routes contains a function designed to modify the background colors of two divs based on the values entered in the respective input fields. However, I am facing two probl ...

Questions about clarifying JS promises and async-await functions

After doing some reading on promises in JavaScript, I have come across conflicting information which has left me with a few basic questions. I have two specific questions that need clarification: Is it necessary for every function in JavaScript to be ca ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

What is the best way to set the value of the days in a month to a div

I've been experimenting with creating a calendar using javascript, HTML, and CSS on my own. I managed to achieve some functionality like obtaining the current month and year as well as the previous month and year by clicking a button in HTML. However, ...

Is there a way to customize the outlined color of an input adornment in MUI?

Looking to customize the default blue color in a Form Control outlined variant, but can't figure out how. I was able to do it with a regular TextField, but this one is a bit trickier. <FormControl variant="outlined"> < ...

Navigating the intricacies of platform-specific settings in JavaScript

Currently, I am in the process of transferring an application from one PHP-based CMS to another (such as Wordpress, Joomla, etc.). I have established classes that enable my code to function seamlessly on each platform without any alterations (so far so goo ...

Adding additional rows to an Array Object in JavaScript based on a certain condition

I am faced with a scenario where I have an array object structured as follows [ { id: 123, startdate: '2022-06-05', enddate: '2023-04-05' },{ id: 123, startdate: '2021-06-05', enddate: '2021-04-05' } ] The task at h ...

Managing data binding for checkboxes within a constantly changing set of options

I'm currently working on designing an angular directive for selecting items from a categorized list. Each item in the list should be selectable using a checkbox. The input data that will be provided to the directive looks something like this: [ { ...

javascript Initiate JSON parsing with preset value

In order to parse JSON into a JavaScript object with data, I am providing a simple example below: var IsTrue = true; var Number = 9; var Object = { a : 1}; var Array = [10,6]; var jStr = '{"ask" : IsTrue, "value" : Number, "obj" : Object, "arr" : Ar ...

Combine filter browsing with pagination functionality

I came across a pagination and filter search online that both function well independently. However, I am looking to merge them together. My goal is to have the pagination display as << [1][2] >> upon page load, and then adjust to <<[1]> ...

ag-Grid incorporating new style elements

For my Angular application, I have a simple requirement of adding a CSS class when a row expands or collapses to highlight the row. I attempted to use gridOptions.getRowClass following the documentation at https://www.ag-grid.com/javascript-grid-row-styles ...

My node.js code is not producing the expected result. Can anyone point out where I may be going wrong?

I've been working on a BMI calculator where I input two numbers, they get calculated on my server, and then the answer is displayed. However, I'm having trouble receiving the output. When I click submit, instead of getting the answer, I see a lis ...

retrieve an item that lacks a definitive value

Here's an object I have: Obj = { foo: false, bar: true, private: { something: 'else' } } Now, I'm trying to return this object without the private part. Since the private part is used elsewhere and cannot be spliced out, I ...

What is the process for uploading a JSON file from your local drive?

I am attempting to use jQuery to load a local JSON file. The code seems to be functioning properly, but for some reason, the data is not being made available in an array. $.getJSON("/ajax/data/myjasonfile.json", function(json) { console.log(js ...

Problem encountered when closing a lightbox on ASP.net using C# during page load

Can you explain the events that are triggered when the ASP.NET page load event occurs? I am currently using a lightbox for some insertion tasks, and after the insertion is complete, I want the parent page to reload with the new value displayed in the gri ...

Experiencing issues with obtaining req.params.id undefined while initiating a put request

Encountering an issue while making a PUT request using Postman, as an error occurs in the VSCode terminal with the message: let product = await Product.findById(req.params.id); ^ TypeError: Cannot read property 'id' of undefined. The request ...

Having trouble with executing functions on an express js Route?

I'm currently exploring Node and Express, and I'm encountering an issue when trying to pass a function instead of plain text on my route. It seems that the documentation only mentions using res.send() method with text. Even when attempting to use ...

Using the MoveToElement and click functions in Protractor with Node.js for automated browser

Trying to click on a checkbox in our application. I have successfully implemented it in Selenium Java using the code below, but struggling to do the same in Protractor Node.js. Any assistance would be appreciated. Selenium- Java : Actions actions ...