vendredi 3 septembre 2021

How to invoke a method using reflection in JavaScript

When I require information from my server I send a packet via a Worker, specifying inside the packet the name of the function to be called when it is returned. The worker sends the packet to the server via a websocket. I use websockets because traffic may be initiated at any time from either side of the connection. When the worker receives a packet from the server it calls the function named in the packet. Example:

function trial() {
    var p = new Packet();
    var c1 = new Command("getGridColumnOptions");
    p.addCommand(c1);
    p.addreturnRoutine("trial_return");
    sendMessage(p);
}

function trial_return(packet) {
    console.log(JSON.stringify(packet));
}

The worker invokes the return function using:

window[packet.returnRoutine](packet);

This has all worked really well until now, but I now have the need to make a call to the server from within a class and to return to a method within that same class.

class Tab {
    constructor() {
    }
    trial() {
            var p = new Packet();
            var c1 = new Command("getGridColumnOptions");
            p.addCommand(c1);
            p.addreturnRoutine("trial_return");
            sendMessage(p);
    }

    trial_return(packet) {
            console.log(JSON.stringify(packet));
    }
}

The worker gets the return but cannot invoke the return method inside the instantiated class. I get

TypeError: window[json.returnRoutine] is not a function

I know this is because I have not qualified the method name with the parent object reference, but I don’t know how to do this, and it will not have been originally instantiated as a global variable.

Any help very gratefully received!





Aucun commentaire:

Enregistrer un commentaire