Javascript inheritance through prototypes results in the addition of supplementary attributes within the descendant classes

When dealing with inheritance in JavaScript, I often encounter a issue where derived classes contain duplicate properties of the base class. And yet, I struggle to understand how to ensure that the derived class leverages the properties of the base class properly. I need some guidance on either refining my approach to inheritance or modifying how I implement prototypical inheritance.

Consider starting with this typical inherit function:

Function.prototype.inheritsFrom = function( parentClassOrObject ){
if ( parentClassOrObject.constructor == Function ) { 
    this.prototype = new parentClassOrObject;  //Normal Inheritance 
    this.prototype.constructor = this;
    this.prototype.parent = parentClassOrObject.prototype;
} else { 
    this.prototype = parentClassOrObject;      //Pure Virtual Inheritance 
    this.prototype.constructor = this;
    this.prototype.parent = parentClassOrObject;
} 
return this;
};

This is likely familiar to you. Now, let's create an inheritance scenario as follows:

function base() {
    this.id = 0;
};

base.prototype.init = function ( _id ){
    this.id = _id;
};

function entity(){
};

entity.inheritsFrom( base );

entity.prototype.init = function( _id ){
    this.parent.init.call( this, _id );
};

Now, we proceed to use the entity class like so:

var e = new entity();
e.init( "Mickey" );
console.log( e.id );

Upon inspecting the properties of the new entity class ... it appears that there are two IDs present (as shown in the output below). Even though this is a simplistic example, I have struggled significantly in resolving this issue.

e: entity
  id: "Mickey"
  __proto__: base
    constructor: function entity(){
    id: 0
    init: function ( _id ){
    parent: base
    __proto__: base

Why am I encountering this duplicated ID situation? The derived class does not even make reference to the 'this.id' property of the base class.

Answer №1

When using the inheritsFrom method and creating a new instance with new parentClassOrObject, the base constructor is called and the id property is set to the prototype. To make necessary changes:

Function.prototype.inheritsFrom = function( parentClassOrObject ){
  if ( parentClassOrObject.constructor == Function ) {
    function tmp() {}
    tmp.prototype = parentClassOrObject;
    this.prototype = new tmp;  //Normal Inheritance 
    this.prototype.constructor = this;
    this.prototype.parent = parentClassOrObject.prototype;
  } else { 
    this.prototype = parentClassOrObject;      //Pure Virtual Inheritance 
    this.prototype.constructor = this;
    this.prototype.parent = parentClassOrObject;
  } 
  return this;
};

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

What is the method to store and retrieve data attributes linked to elements such as select options within the React framework?

Despite my efforts, I'm currently unable to retrieve the data attribute from an option using React as it keeps returning null. <select onChange={(e) => this.onIndustryChangeOption(e)} value={this.props.selectedIndustry}> <opti ...

a method for inserting a space after a certain character, with the exception of when that character is located at the start or end of a line

I've created a regular expression that can modify various patterns like: anything1 * anything2* anything3 anything1* anything2 * anything3 anything1 * anything2 * anything3 anything1*anything2 *anything3 anything1 * anything2 *anything3 anything1*any ...

The "Splash Screen Div" page displayed during transitions and page loading

Creating a "Splash Screen Div" for a loading page involves waiting until everything is loaded and then hiding or moving the div off screen. Below is an example: index.html <div id="loading-Div"> <div id="bear-Logo"> < ...

What measures can I take to hide the browser's rendering of an image?

I've noticed that when I insert new images into the DOM, occasionally I can observe the image being displayed in a top to bottom manner. Is there a simple JavaScript method or event handler that I could utilize to ensure that the entire image only app ...

Tips for updating the values of 'Sec-Fetch-Dest', 'Sec-Fetch-Mode', 'Sec-Fetch-Site', and 'Sec-Fetch-User' using Axios

I'm having trouble figuring out how to set specific values for the 'Sec-Fetch-Dest', 'Sec-Fetch-Mode', 'Sec-Fetch-Site', and 'Sec-Fetch-User' headers when making a request through an axios instance in Vue. Unfo ...

difficulty encountered during json parsing

I need help accessing displayName in req When I use this code snippet: console.log(req.session.passport.user._raw) The following information is displayed: { "kind": "plus#person", "etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/XiR7kPThRbzcIw-YLiAR ...

Is it possible to utilize AngularJS without relying on a REST API?

While I am comfortable using the view engine (such as jade) and controllers to provide data on a simple website created with node.js, integrating AngularJS as the client framework seems to require implementing a REST API on the backend for data retrieval. ...

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

Navigate through different dates with a scrolling carousel

After developing a carousel for users to flick and scroll through dates using the slick library, I've encountered some minor issues as well as a major one. Take a look at the carousel on this link: Username: test Password: test I'll outline t ...

transmitting user data to specified div container

Hey there, I have a question about sending user input to a div section in an HTML document. I've asked this before, but now I'm trying to be more specific. I'm having trouble getting the user input to display below each other in the div whe ...

Error encountered in Listings#index with ExecJS RuntimeError

Upon launching my localhost, I encountered an ExecJS error message that has left me puzzled. Any assistance would be greatly appreciated. A Glimpse into My Localhost The issue originates from /.../conektec/app/views/layouts/application.html.erb, specific ...

Customizing split applications on Windows 8

Windows 8 split app displays tiles with images, and I want each tile to show a different image. Below is the code from the default.html page: <div class="item"> <img alt="some text" data-win-bind="source: imagePath"> <div class="item-overl ...

What steps can we take to create a personalized PDF editor incorporating our unique edit functionalities using Vue.js?

Is it possible to create a PDF editor similar to MS Word using vuejs? How can I implement custom logic in the PDF editor with vuejs? For example, the features should include: Conditional replacement of text Adding tags to text within the PDF Changing the ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

VueJS nested ajax requests successfully fetching data but failing to display content on the view

I am facing a situation where I need to retrieve additional data after the initial ajax call (in the mounted function) in Vue.js. I have placed the second ajax call within an if condition and inside the success function of the first ajax. The data is succ ...

Tips for implementing a client-side event when an asp:menu item is clicked

Currently, I'm incorporating the <asp:Menu> control into my website and populating it with data from a table in my Sql Server database using an XML data source. Now, I am looking to implement a client-side event when a user clicks on a menu item ...

Is there a way to retrieve all values in the pathname from a URL after the initial slash

Extracting pathname pathname: "/kids/dlya-malyshey/platya-i-yubki" By using the substr function, I will remove the initial slash location.pathname.substr(1,); Now, the result is kids/dlya-malyshey/platya-i-yubki The challenge is to extract all ...

What is the best way to utilize a JavaScript variable as a background within an inline style sheet?

I have a fun project for this evening - I am trying to make my website load a different background image every time the page is refreshed. Earlier on in this project, I managed to make the background interact with window size and screen resolution similar ...

Limiting the length of parameters in an Angular directive

Is there a character limit for the parameter being sent to this directive? I'm encountering an issue with my code: header = JSON.stringify(header); columnObj = JSON.stringify(columnObj); $compile('<div column-filter-sort header=' + heade ...

What is the significance of the "#" character in the URL of a jQuery mobile

As I encounter a strange issue with my jQuery mobile page, I notice that when accessing page.php everything looks good, but once adding #someDetailsHere to the URL, it only displays a blank white page. What could be causing this and how can I resolve it? ...