Instructing one class to delegate its redirect functions to another class

Within my JavaScript code, I have a class called class1 that takes in another class called class2 as a parameter in the constructor.

My goal is to be able to access all the functions of class2 directly from class1, without having to manually declare each function in class1 and then call it on class2.

Is there a smart and efficient way to achieve this?

Answer №1

One approach is to implement a Proxy:

class Worker {
    constructor(name) {
        this.name = name
    }
    method1() {
        console.log(this.name, 'method1')
    }
    method2() {
        console.log(this.name, 'method2')
    }
}


class Facade {
    constructor(worker) {
        this.worker = worker
        return new Proxy({}, this)
    }
    get(target, prop) {
        return prop in this.worker ? this.worker[prop] : this[prop]
    }
    ownMethod() {
        console.log('facade own method')
    }
}

let f = new Facade(new Worker('worker1'))

f.method1()
f.method2()

f.ownMethod()

Another method is to replicate method references to the facade object:

class Worker {
    constructor(name) {
        this.name = name
    }
    method1() {
        console.log(this.name, 'method1')
    }
    method2() {
        console.log(this.name, 'method2')
    }
}


class Facade {
    constructor(worker) {
        this.worker = worker
        for (let func of Object.getOwnPropertyNames(worker.constructor.prototype))
            this[func] = worker.constructor.prototype[func].bind(worker)
    }

    ownMethod() {
        console.log('facade own method')
    }
}

let f = new Facade(new Worker('me'))

f.method1()
f.method2()

f.ownMethod()

In Typescript, you can utilize f = ... as (Facade & Worker) Playground Link, but there could be more effective solutions.

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 bootstrap function for showing the modal with the ID "myModal" is malfunctioning

As someone who is just getting started with PHP and Bootstrap, I am running into an issue where the modal doesn't seem to work when triggered using the .modal method. Here is the PHP code I am using: if ($show_login_modal) { echo " <scr ...

Linking Java objects with Node.js variables

In this snippet of code, I am utilizing the 'java' module in node.js to create Java objects. Specifically, I am creating four Java objects and aiming to consolidate them as a single object by using the variable 'args' to store these Jav ...

Establishing a Next.js API endpoint at the root level

I have a webpage located at URL root, which has been developed using React. Now, I am looking to create an API endpoint on the root as well. `http://localhost:3000/` > directs to the React page `http://localhost:3000/foo` > leads to the Next API end ...

Incorporate data from a CSV file into an HTML table on the fly with JavaScript/jQuery

I have a CSV file that is generated dynamically by another vendor and I need to display it in an HTML table on my website. The challenge is that I must manipulate the data from the CSV to show corrected values in the table, only displaying products and not ...

Displaying a static image on an HTML5 canvas without any movement

As a novice in canvas game development, I must apologize for my lack of knowledge. I have an image with dimensions 2048px width and 1536px height that needs to be placed within a canvas (the width and height vary on different devices). While I am able to ...

How do you properly include a new property in an Object using Typescript?

I am currently delving into the world of typescript. After exploring various sources like this one and that one, as well as trying out multiple solutions, I have encountered a challenge. I have a variable named incomingArticleObject which needs to be of ty ...

How to use the sha512 hash function in Node.js for Angular2 and Ionic2 applications

I'm attempting to generate a SHA512 Hash in Angular2 (Ionic2) that matches the PHP function hash('sha512'). After trying out different modules like crypto-js, crypto, and js-sha512, I keep getting a different Hash compared to PHP. I even a ...

Ways to update HTML content generated by Ajax

Having some difficulties modifying the HTML content generated by AJAX. This is the code snippet from the page: @model IEnumerable<WE_SRW_PeerNissen.Models.Reservations> @{ ViewBag.Title = "List"; Layout = "~/Views/Shared/_Layout.cshtml"; } ...

Converting User Input Special Characters to HTML5 data-attributes with URL Encoding/Decoding

Seeking assistance from the experts on my first question here at stackoverflow. Our web application allows users to input escape/special characters, and we are conducting testing for extreme scenarios. I have successfully passed escape characters through a ...

The child component's useEffect is not triggered when rendering the parent component with the <Link> element

I am facing an issue with my parent component that contains a child component. I have set up a route for the parent component in the main app and now I need to access this parent component from another page using the Link component. However, I am encounter ...

Fixed Navigation Menu on Top with Specific Width Size

Currently diving into the world of CSS and eagerly following a tutorial on creating a responsive menu for my website. Managed to get it up and running, but hit a few roadblocks along the way: The navigation menu seems to shrink in both desktop and mobile v ...

What could be causing the jQuery effect to not function properly?

After completing a course on Codecademy, I successfully ran the code. However, I prefer to copy and paste the code into my own jquery folder for future reference and practice. The objective of this project was to make the element 'krypton' bounc ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

Converting Dynamo DB stream data into Json format

I need to convert the DDB stream message into a standard JSON format. To achieve this, I am using unmarshalleddata = aws.DynamoDB.Converter.unmarshall(result.NewImage); where result.NewImage is { carrier: { S: 'SPRING' }, partnerTransacti ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

I am looking to personalize a Material UI button within a class component using TypeScript in Material UI v4. Can you provide guidance on how to achieve this customization?

const styling = { base: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', border: 0, borderRadius: 3, boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)', color: 'white', height: 48, ...

Exploring TypeScript: Implementing a runtime data mapping in place of an interface

Take a look at this code snippet that defines two command handlers for a server: import { plainToClass } from "class-transformer"; enum Command { COMMAND_1, COMMAND_2, } class Command1Data { foo1!: string } class Command2Data { foo2!: ...

Choose a single asset from the list of values stored in the Map

I'm looking to implement something similar to the following: let myMap = new Map<string, any>(); myMap.set("aaa", {a: 1, b: 2, c:3}); myMap.set("bbb", {a: 1, b: 2, c:6}); myMap.set("ccc", {a: 1, b: 2, c:9}); let cs = myMap.values().map(x => ...

You can't retrieve a JSON object using Javascript

Every time I execute the javascript/php code below, I encounter an issue where I keep receiving "undefined" when trying to alert the 'userid' property of the json object. However, if I turn the json object into a string using stringify(), it corr ...

io.emit is unable to send messages to all connected clients

Struggling to implement a feature in a socket.io game where players can leave the game, I'm facing an issue with io.emit only notifying the departing player. Here's the snippet from my socket.js: io.on("connection", sock => { sock.on(&ap ...