In the JavaScript example provided, do child classes inherit their parent class prototype?

Here's the code I'm working with:

class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }
}

Rectangle.prototype.area = function () {
  return (this.w * this.h);  
};

class Square extends Rectangle {
    constructor(w, h) {
        super(w,  h);
        // this.w = w;
        // this.h = h;
    }
}

Am I facing any issues with my inheritance implementation?

I attempted to utilize the following:

const rec = new Rectangle(3, 4);

const sqr = new Square(3);

console.log(rec.area());

console.log(sqr.area());

The output for rec is correct, however sqr outputs: NaN

I also experimented by adding a Square prototype:

Square.prototype.area = function () {
  return (this.w * this.w);  
};

but then the output becomes:

-1  
-1 

This modification seems to have affected the area calculation for rec.area() as well.

Answer №1

When creating a Square, the constructor is called with only one argument since all sides are equal in length. To convert this to a Rectangle constructor call, which requires two arguments (width and height), you simply need to provide the same single argument twice when constructing the Rectangle:

class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }
    area() { // Use this notation for prototype methods
        return this.w * this.h;  
    }
};

class Square extends Rectangle {
    constructor(w) { // One argument...
        super(w, w); // ...Two arguments, where width equals height
    }
}

let square = new Square(10);
console.log(square.area());

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

Having issues with validating a form using Yup for a Checkbox input?

My form is built using mui, formik, and yup. If the input fields are empty (e.g. "surname") after clicking the submit button, an error is displayed. However, the issue arises when the checkbox for Terms of Service isn't checked as no error shows up. ...

Encountering a DOM exception with React 16.6 due to lazy loading/Susp

I am currently working on implementing dynamic import in my React application. Most of the React examples I have seen involve rendering the application to a specific tag and replacing its content, like this: ReactDOM.render(<App />, document.getEle ...

Ways to transfer a state from the child component to the app component

I have 2 different components that contain sub-components within them. In one of these components, I'm trying to figure out how to transfer the click event from the sub-component to another component so that it can render an entirely new component for ...

How can I use VueJS Cli to create a shared variable that is accessible across all pages and can be monitored for changes within a specific page?

Recently, I've delved into the world of VueJs and I'm encountering some issues with a project that I can't seem to resolve through online resources. I am trying to establish a variable that is common across all pages (month), and whenever t ...

Unable to eliminate user registration feature with Meteor and React

Exploring the world of Meteor and diving deep into its functionalities, I am currently focused on creating a user login and signup page with personalized control panels for each registered user. Although I have successfully implemented the signup and logi ...

Fetching data in React using AJAX

I am in the process of developing a React Component that will display data retrieved from an AJAX call. Here's my scenario - I have a Jinja Flask back end hosted on AWS API Gateway, which requires custom headers and the Authorization header to serve H ...

Tracking the progress of reading position using Jquery within an article

Here is an example of a reading progress indicator where the width increases as you scroll down the page: http://jsfiddle.net/SnJXQ/61/ We want the progress bar width to start increasing when the article content div reaches the end of the article c ...

Encountering a mixed content error in Internet Explorer 8 due to the Nivo slider jQuery?

I am encountering an issue with the Nivo jQuery slider on my HTTPS website, as it appears to be generating a mixed content error in Internet Explorer 8. Despite posting on the Dev7 Studios forum and conducting extensive research on the IE 8 mixed content ...

Unable to locate "Gruntfile.js" Node module for task execution

I am currently in the process of developing a module that enables node to execute Grunt tasks via the command line. This Node module is globally installed at : C:\Users\pcharpin\AppData\Roaming\npm\node_modules\task-app ...

The variable in the dataTables JavaScript is not receiving the latest updates

//update function $('#dataTable tbody').on('click', '.am-text-secondary', function() { //extract id from selected row var rowData = table.row($(this).parents('tr')).data(); var updateId = rowData.id; ...

What is the best way to create three buttons for selecting various parameters?

I have a code snippet where I want to assign different parameters to each button when clicked. However, despite my logic, the functionality is not working as expected. Can someone help me with the correct syntax? For example, if I click the "Start (Easy) ...

Having issues retrieving a JSON array in PHP with the json_decode function

Can someone assist me with passing and returning an array to a PHP script? I have successfully tested the json_encode portion, but I am facing issues with the json_decode on the PHP side. Javascript scid_list = []; $('.filter_on').each ...

What is the best method for encrypting a URL that contains AngularJS data?

Here is the URL that needs to be encrypted: <a class="btn btn-success btn-sm btn-block" href="@Url.Action("myAction", "myController")?Id={{repeat.Id}}&HistoryId={{repeat.HistoryId}}" ng-cloak>View History</a> I am seeking guidance on enc ...

Troubleshooting jQuery's issue with dynamically adding input fields

I came across a tutorial (which I tweaked slightly) on this website: code In JSFiddle, everything works perfectly fine with the code. However, when I implemented it on my actual page, it's not functioning as expected. I've been trying to trouble ...

Place the outcome of the function into the div element's attribute

As a newcomer to HTML and JavaScript, I recently dove into using 3Dmol.js. Following a tutorial, I was able to create this code snippet that actually works: <script src="http://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script> <div id="el ...

Navigating following a JQuery AJAX request in PHP

After clicking the login button, I utilize JQuery's POST method to retrieve data from login.php to check if the login was successful. If it fails (no user found), the appropriate message is displayed. However, when attempting to redirect a user (whic ...

What is the method for retrieving information from a JSON file that has been uploaded?

I am working with some HTML code that looks like this: <input type="file" id="up" /> <input type="submit" id="btn" /> Additionally, I have a JSON file structured as follows: { "name": "Jo ...

Validating properties of a class using Typescript's Class-Validator

I tried using the class-validator decorator library for validation processes on my sample project. However, it doesn't seem to be working as expected. The sample project aims to create projects based on user inputs, and I'm attempting to validate ...

Have you ever encountered issues with Promises.all not functioning properly within your vuex store?

I'm currently experiencing an unusual problem. In my Vue project, I have a Vuex store that is divided into different modules. I am trying to utilize Promise.all() to simultaneously execute two independent async Vuex actions in order to benefit from th ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...