Executing a Parent Method from an Overridden Method in a Child Class

Is it possible to call a method from a parent class that has been overridden in the child class? Below is an example where I want to access the bar.my_name() method from within the foo.my_name() overriding method.

function bar() {
  this.my_name = function() {
    alert("I Am Bar");
  }
}

function foo() {
  this.my_name = function() {
    alert("I Am Foo");
    //access parent.my_name()
  }
}

foo.prototype = Object.create(bar.prototype);
foo.prototype.constructor = foo;

var test = new foo();
test.my_name();

Answer №1

Here's a way to approach it:

(new bar()).my_name.call(this);

Your understanding of prototypes may need clarification, as they might not be beneficial in this situation.

An alternative method could be:

var bar = {
    my_name: function () {
        console.log('bar name');
    }
};

var foo = Object.create(bar);

foo.my_name = function () {
    console.log('foo name');
    bar.my_name.call(this);
};

If constructors are preferable, consider something like the following:

function Bar () {}

Bar.prototype.my_name = function () {
    console.log('bar name');
};

var foo = Object.create(Bar.prototype);

foo.my_name = function () {
    console.log('foo name');
    bar.my_name.call(this);
};

Without more context on your goals, it's challenging to provide tailored advice.

Answer №2

To solve this issue, one approach could be transferring the method to the prototype of the base class.

function bar() {
}

bar.prototype.my_name = function() {
  alert("I am bar");
}

function foo() {
}

foo.prototype = Object.create(bar.prototype);
foo.prototype.my_name = function() {
    alert("I Am Foo");
    bar.prototype.my_name.call(this);
}

foo.prototype.constructor = foo;

var test = new foo();
test.my_name();

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

Reading environment variables in Next.js (specifically in an Azure App Service)

We need to deploy the identical image to various environments (development, quality assurance, production). Our nextjs application is deployed on Azure app service and we intend to retrieve azure app settings as part of the configuration. We are unable t ...

Remove the color options from the Material UI theme

Can certain color types be excluded from the MUI palette in MUI v5? For example, can background and error colors be removed, allowing only colors defined in a custom theme file to be used? I attempted using 'never' but it did not provide a solut ...

Deciphering the node.js code: Understanding the significance of the syntax `(res) =>`

Would someone be able to clarify the syntax used in the nodejs docs for me? I'm having trouble understanding this particular line: (res) => { ...

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

What is the best way to retrieve the value of a textbox in AngularJS?

Trying my hand at creating a basic web page using angular. I've got 2 textboxes and 2 buttons - one to set a predefined value in a textbox, and the other to add some text. Here's the code snippet: <!DOCTYPE html> <html lang="en" ng-app ...

Unable to access an HTML element using refs within the render() method

Currently, I am working on developing a graphics editor using ReactJS. One of the main components in my project is the Workspace component. This particular component is responsible for drawing objects on the canvas element. The Workspace component is imple ...

Uncovering unseen tags generated by JavaScript on a webpage using Python

I have THIS LINK page that contains javascript. To view the javascript, simply click on show details. How can I extract data from this URL source? Should I use re? Here is what I attempted with re: import urllib import re gdoc = urllib.urlopen('Tha ...

When attempting to install material UI in my terminal, I encounter issues and encounter errors along the way

$ npm install @material-ui/core npm version : 6.14.4 Error: Source text contains an unrecognized token. At line:1 char:15 $ npm install <<<< @material-ui/core CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException ...

Connect main data to sub-component

Example Vue Structure: <Root> <App> <component> Main function in main.js: function() { axios.get('/app-api/call').then(function (resp, error) { _this.response = resp.data; }) ...

Refresh the page once the function has been executed

Recently, I came across a basic javascript code that I need some help with. I want to reload the page after certain elements have faded out and back in. The problem is, I'm not sure where exactly I should include the window.location.reload(); function ...

Reversing the order of input-group-addon and input in bootstrap on mobile devices

I attempted to adjust the layout of a bootstrap input-group-addon on mobile devices by using two input elements and manipulating their display and visibility properties. From a design standpoint, I achieved the desired result as the input is now positione ...

The concept of 'this' remains undefined when using a TypeScript Property Decorator

I've been delving into TypeScript decorators focusing on properties, and I crafted the following snippet inspired by various examples: decorator.ts export function logProperty(target: any, key: string) { let val = this[key]; const getter = () ...

"Encountering issue with the find() function following a successful outcome

I am encountering some issues with my extension. In the following code snippet, I am using a find() function to extract data from an external page: $.ajax({ url: 'http://www.subspedia.tv/traduzioni.php', success: function(data) { ...

The requested resource in Mean stack does not contain an 'Access-Control-Allow-Origin' header

I recently integrated cors & body parser into my project. Below is an excerpt from my authSrvice.js file: resetemail(emailid) { let headers = new Headers(); headers.append('Content-Type','application/json'); return this.ht ...

Am I utilizing the htmlspecialchars function properly?

My main objective is to protect the user from malicious code and prevent XSS attacks. I have implemented a series of checks to filter the user's input before storing it in the database. The user input is stored in the $post variable. $post = htmlspec ...

Is it possible to import a component from a production build of create-react-app?

Has anyone tried importing a component from a production build of create-react-app? Situation: I have one CRA project that has been built for production. Inside this project, there is a component named ExampleButton. Now, I am working on a second CRA pro ...

Guide on how to showcase an array in a string format using table rows in JavaScript or jQuery

After making an AJAX call to a PHP database, I receive a String as a result in my script. The format of the string is shown below: array(4) { [0]=> array(3) { ["id"]=> string(3) "181" ["number"]=> ...

Is there a way to transform an array of strings into an object?

I am currently working on displaying an array using ng-grid and I am encountering some issues. Here is the link to the code: http://plnkr.co/edit/G33IlPCNAdh1jmNTtVNO?p=preview It seems that ng-grid requires a JSON object instead of an array for the field ...

Understanding React: Why 'props' Property Cannot Be Read

Recently, I made the decision to delve into learning React and chose to begin with the official tutorial. Everything was going smoothly until I reached a specific portion of my code: var CommentBox = React.createClass({ render: () => { return ( ...

Is there a way to verify if a React hook can be executed without triggering any console errors?

Is there a way to verify if a React hook can be invoked without generating errors in the console? For example, if I attempt: useEffect(() => { try { useState(); } catch {} }) I still receive this error message: Warning: Do not call Hooks i ...