Understanding JavaScript's Inheritance

My current Person class looks like this:

 class Person {
    constructor(name, age, gender, interests) {
        Object.assign(this, {name, age, gender, interests});
    }
}

I have also created a sub-class Teacher which inherits properties from the Person class:

class Teacher extends Person {
    constructor(name, age, gender, interests, subject, grade) {
        super(name, age, gender, interests);
        Object.assign(this, {subject, grade});
    }
}

However, I am now wondering about creating a new sub-class that does not inherit all properties from the Person class. For instance, I do not want to include the interests property. Would it be correct to exclude it like this:

class Student extends Person {
    constructor(name, age, gender, height, weight) {
        super(name, age, gender); // I chose not to include the interests property here
        Object.assign(this, {height, weight});
    }
}

As someone who is still learning, I am unsure if this approach is considered best practice. Thank you and have a wonderful day!

Answer №1

  super(name, age, gender); // The 'interests' property is not included here

If an argument is not added to a function call, the parameter will be implicitly undefined. This means the line now reads:

 super(name, age, gender, undefined)

So, while the interests property still exists, its value is now undefined. This approach can work well if your code assumes that interests may not always be defined. However, if you perform calculations without explicitly checking for interests, you may run into issues such as getting unexpected results like NaN:

  if(person.age > 18) {
   alert("adult");
  } else alert("child"); // What if the person's age property was just not set?

Instead of setting the existing property to indicate it is undefined, you could consider omitting the interests property entirely by:

1) Moving it to a subclass:

 class Person {
   constructor(name, age, gender) {
    Object.assign(this, {name, age, gender });
  }
 }

 class PersonWithInterests extends Person  {
   constructor(name, age, gender, interests) {
    super(name, age, gender);
    Object.assign(this, { interests });
  }
}

2) Creating a Mixin:

A Mixin is a class that can extend multiple classes. If more than one Person has an interest, creating a mixin might be advantageous:

 const Interested = Super => class InterestMixin extends Super {
  constructor(args) {
    super(args);
    this.interests = args.interests;
  }
};

class Animal { }

const PersonWithInterest = Interested(Person);
const AnimalWithInterest = Interested(Animal);

new PersonWithInterest({ name: "Jonas", interests: 10 })
new AnimalWithInterest({ type: "bear", interests: 20 })

(If you find yourself creating a new Mixin for every single property, this approach may become less practical. In such cases where grouping properties into a useful Mixin is not possible, opt for the first method instead (using optional properties)).

Answer №2

Inheritance is the concept of receiving characteristics or properties from a parent entity. It is not advisable to completely avoid attributes passed down from a parent object (and it may not even be possible).

Here are two potential solutions:

  • From an architectural perspective (which is highly recommended): in this specific scenario, one could simply place the interests attribute within the Teacher class. If other classes also require the interests attribute, consider creating a sub-class like PersonInterest that can be inherited by the Teacher class.
  • Alternatively, at the code level: you have the option to set the interests attribute to null or undefined within the class where it is not needed.

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

Transform XLS files into JSON format seamlessly by leveraging the power of Sheetjs and FileReader.js

I have been attempting to transform an uploaded XLSX file into JSON format using https://github.com/bgrins/filereader.js for handling the upload process and https://github.com/SheetJS for the actual conversion of the file. Below is the code I am currently ...

Incorporating traditional Javascript classes for modeling in React development

Can traditional JavaScript classes be utilized in models within the MVC framework while using React, as opposed to relying on Redux or contexts & reducers which may impact reusability? If this approach is feasible, how can we efficiently 'subscribe&ap ...

Encountering a 'require is not defined' issue while trying to implement chartjs within a JavaScript script

I am new to using Node.js and JavaScript. Currently, I am working on integrating chartjs into my project. Below are the HTML and JavaScript files associated with my project: charts.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <hea ...

Using React with Typescript to display components generated from the `map` function

In my scenario, I have retrieved data from a JSON file and am also utilizing a utility function that selects 5 random entities from an object Array. This particular array contains 30 entities. Struggling with displaying the 5 random jockeys stored in the ...

Trigger a click event on a div element that is nested within a form

Having trouble displaying an alert when clicking on a disabled button because the user needs to first click on a terms checkbox. Here's my jQuery code: $('#divButton').on("click", function() { if ($('#buybutton').prop('d ...

Javascript Form Verification (beginner coder)

I am having issues with my HTML form validation using JavaScript. Everything was working fine until I added the regular expression match part. Now, whenever the submit button is clicked, the page refreshes without performing any of the form validation belo ...

POST request returned a null response in the xhr.responseText

Check out the structure of my JavaScript code: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://myajaxurl.com/lyric", true); var data = "lyric"; xhr.onreadystatechange = function() { if (xhr.readyState == 4) { console.log(xhr.responseText); ...

HTML5's drag-and-drop feature, including nested targets, allows for intuitive and interactive user

I'm currently implementing HTML5 drag and drop functionality. I have a parent div that is droppable, and inside it, there is another child div that is also droppable. <div id="target-parent"> <div id="target-child"></div> </d ...

Utilize JavaScript to parse JSON response data, calculate the average of a specified field while keeping track of

The data returned from the API call is structured as follows: var array = {"scores":[ { userid: "1", mark: 4.3 }, { userid: "1", mark: 3.8 }, { userid: "2", mark: 4.6 }, { userid: "2&quo ...

Exclude the data key from form submission based on condition in React

Is it possible to omit the onSubmit value if a checkbox is selected, without requiring a specific label/input? For example, when the indefinite runTime box is checked, the key runTimeSeconds doesn't need to be included in the payload. Can this logic b ...

Whenever I attempt to use window.print(), the styling gets completely messed up. I've experimented with both @media screen and @media print, but unfortunately, I

I am working on creating an invoice, the design looks perfect in the browser, but when I try to window.print() the style gets corrupted. I attempted to include @media screen and @media print, but I am still facing the same issue. The invoice form is incorp ...

What is the goal of JSON.parse(JSON.stringify(x))?

During my recent project work, I stumbled upon the following code snippet: let newParams = JSON.parse(JSON.stringify(initialParams)); I'm curious - what exactly does this code achieve? ...

Utilizing AJAX in Django applications

I'm currently working on integrating a basic AJAX function with Django, but I seem to be facing some issues. The request.is_ajax() function is returning False, and using event.preventDefault() doesn't prevent the form from getting submitted. Her ...

The code snippet for the React TypeScript Cheatsheet in the Portal sample appears to be malfunction

I have implemented a strict version of TypeScript and ESLint in my project. The code for this portal was originally sourced from the documentation available here: After making some modifications, the code now looks like this: import React, { useEffect, u ...

Send a pair of selected options from dropdown menus to a service using Angular

I have created a component that needs to pass two values from two separate dropdowns to my service on button click. Here is the code for my component: import { Component, Input, OnInit } from '@angular/core'; import { CategoryType } from '. ...

What is the process for retrieving paginated data from the store or fetching new data from an API service within an Angular 2 application using ngrx-effects?

After coming across this insightful question and answer about the structure of paginated data in a redux store, I found myself pondering how to implement similar principles using ngrx/store in an angular 2 application. { entities: { users: { 1 ...

checking the validity of serialized information in Ajax

I am facing a specific issue where I need to validate data before it is saved through an ajax call. When the user switches to a different URL, the save_ass_rub function is triggered. Within my application, there is a custom Window that allows users to inp ...

What is the reason behind the length property belonging to an array object?

While there are other instances, let's focus on the length property for now. Why does it appear as if we're copying it here: [].hasOwnProperty("length") //==> true It is common knowledge that an array's length property belongs ...

The error message "req.body undefined in NEXT JS" pops

Feeling lost and confused? I'm encountering an 'undefined' issue while attempting to upload my form data to Supabase. The data is being passed as undefined to the API, but when I inspect it within the submit handler, it displays correctly b ...

Can you explain how to utilize a function on a client component in Next.js?

I'm a bit lost on how client components function. I am working on an image uploader project where I need to extract the userId from supabase, utilize the supabase server function, and then upload the image to supabase storage with the "userId/filename ...