Combining two classes into a single class using ‘this’ in JavaScript

I'm encountering an issue where I am unable to figure out how to extend from the third class. So, I really need guidance on how to call the A class with the parameter 'TYPE', extend it with C, and then be able to call getType() with class C. Any suggestions or solutions?

const TYPE = 'TYPE'

class A {
    constructor(type) {
        this.type = type;
    }
    
    getType() {
        return this.type;
    }
}

class B {
    constructor(id) {
        this.id = id;
    }
    
    getId() {
        return this.id;
    }
}

class C extends B {
    constructor(id) {
        super(id);
        
        //Here should be a function that should bind the method from class A
    }
}

const c = new C(1);
console.log(c.getId())
console.log(c.getType())

Answer №1

const TYPE = 'TYPE'

class A {
    constructor(type) {
        this.type = type;
    }
    
    getType() {
        return this.type;
    }
    
    extend(extendedClassInstance){
      extendedClassInstance.type = this.type;
      extendedClassInstance.getType = this.getType.bind(extendedClassInstance)
    }
}

class B {
 constructor(id) {
        this.id = id;
    }
    
    getId() {
        return this.id;
    }
}

class C extends B {
    constructor(id) {
        super(id);
        (new A(TYPE)).extend(this) 
    }
}

const exampleC = new C(1);
console.log(exampleC.getId())
console.log(exampleC.getType())

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

The HTTP request arrives with no content within the body

I am in the process of developing a basic client-server application using Node and Express. The goal is for the program to receive a JSON input on the client-side, perform some operations, and then send data to the server-side. Currently, I am able to sen ...

Encountering memory leaks and displaying repetitive data due to having two distinct observables connected to the same Firestore

I am currently utilizing @angular/fire to retrieve data from firestore. I have two components - one serving as the parent and the other as the child. Both of these components are subscribing to different observables using async pipes, although they are bas ...

What is the best way to clear a MongoDB objectId field, set it to null, or ultimately remove it from a

Custom Modal Schema : { "title":{type:String,required:true}, "genre":{type:mongoose.Schema.Types.ObjectId,ref:"Genre"} } Upon creating a document using this schema, the document structure appears as follows: { "_id":ObjectId("5abcde12345fgh6789ijk ...

Mastering the art of nested await functions in JavaScript

In my current Nodejs application using mongoose, I am implementing cache with MongoDB in-memory and MongoDB database. This setup is running on Nodejs 8.9 with async/await support enabled. let get_func = async(userId) => { let is_cached = await c ...

What is the best way to integrate custom JavaScript files into a Vue project?

I recently downloaded an HTML template from a website and now I am looking to convert the entire template into a Vue CLI project. The template includes jQuery and other custom JavaScript files. While I was able to use npm packages for jQuery and Bootstrap, ...

Extracting data from the response object and injecting it into the request

Once the file has been successfully uploaded, the 'uploadSuccess' callback event is triggered, providing information about the newly created media. The 'hashed_id' value within this object is crucial for my PUT request. I attempted to ...

Display a modal pop-up containing HTML content

I recently started building a small website using Zurb Foundation. I have created a basic grid layout with large metro style div thumbnails (about 10 on the page). Now, I want to enhance user interaction by implementing modal windows that appear when a th ...

Identify the specific element using a designated data attribute

Having trouble figuring out how to select a specific element with a particular data attribute. In my situation, I want to target the a element with class="zoom-image" and data-order-item-id="<?=$order_item_id ?>". Here is the HTML/PHP code snippet ( ...

Format specific words or characters in a text input

In HTML, when I want to display strings in a Text Input or TextArea, I am looking for a way to have specific substrings render with a box around them. I envision these boxed substrings as being treated as a single entity, similar to how highlighting or tex ...

The act of transmitting data via a timer using JS WebRTC leads to crashes if the page is reloaded before

In one of my server.js files served by a node, I have written the following code snippet: function multiStep(myConnection, data) { var i=0; var myTimer=setInterval(function() { if (i<data.length){ var element=JSON.string ...

Enhance and streamline custom module code within a Node.js Express application

I am seeking suggestions on how to optimize the code within my custom module. Below is the code for my module which you can review and provide feedback on. var employee = { all: function (req, res) { jwt.verify(req.token, 'novatureso ...

Tips for waiting for a function to finish executing in node.js (using a for loop)

Currently, the issue lies in the fact that the for loop instantly loops through everything. However, I want it to pause before looping because each time the loop runs, it inserts data into the database (which takes time). Therefore, I would like it to wait ...

Executing 'npm run bundle' with Webpack results in an ERR! with code ELIFECYCLE

As someone new to using Webpack with AngularJS apps, I am eager to learn but facing some challenges. Following the guide by Ken Howard has been helpful, but I encounter an error when attempting to run the bundle. Article by Ken Howard that I've been ...

How can I implement a toggle button to display additional details for a specific row within a table created using React.js?

I'm currently working on a project using Next.js and have come across an unexpected issue. Upon reading a JSON file, I populate a table with the data retrieved from it. Each piece of information in the table has hidden details that should only be reve ...

Adding JSON content to a form for editing functionality within an Angular 8 CRUD application

I am currently working on building a Single Page Application using Angular 8 for the frontend and Laravel for the backend. I have been able to successfully pass data to the backend via JWT, and everything is functioning as expected. The application follows ...

Changing a get request to a post request: A step-by-step guide

I have been utilizing the following script: $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', start: function(){ $("#success-result").html("loading...."); }, update : function ( ...

Persist form input data using ajax without any back-end server logic involved

Is there a solution for saving basic form data from a static webpage without using any server-side code? I have thought about potentially using MongoLab through a RESTful interface, but that would mean exposing API credentials on the client side and the ...

Retrieve data from a ng-repeat variable within a controller

Below is the current code snippet: HTML <center><li ng-repeat = "x in items | orderBy: 'priority'"> <!-- color code priorities --> <span ng-style="cmplt" ng-class="{ red: x.type == &apo ...

jQuery plugin modifies keypress events

I have integrated the Jquery ImgAreaSelector plugin into my website. Within my site, I have implemented several keypress triggers using jquery. For example: $(document).bind('keypress', 'S', function(){ alert("You have pressed S key ...

Tips for creating a filter in React JS using checkboxes

In my current situation, I have a constant that will eventually be replaced with an API. For now, it resembles the future API in the following way: const foo = { {'id':1, 'price':200, 'type':1,}, {'id':2, &apo ...