mercredi 11 mars 2020

Variables, scopes and structure in javascript

I have a question about variables/references, scopes and structure in javascript. Please consider the following example:

In file start.js:

const WsClass= require('./wsClass');
let wsc = new WsClass('ws://127.0.0.1:4141');
wsc.subscribe();

In file wsClass.js:

let _staticWsClass = null;

function WsClass(websocketUrl){

    this.subscribe = function() {
        subscribe();
    };
    function subscribe() {

        try {
            let ws = new WebSocket(websocketUrl);
            prepareListeners(ws);

            ws.on('open', function open() {

                ...
            });

            ws.on('close', function close() {
                subscribe();
            });

        } catch (err) {
            ...
        }
    }

    function prepareListeners(ws) {

        const WebSocketEmit = new WSemitter();

        WebSocketEmit.removeAllListeners('doSomeThing');
        WebSocketEmit.on('doSomeThing', function () {
            execute(ws);
        });
    }

    function execute(ws){
        ...
    }
}

function create(websocketUrl) {
    if (_staticWsClass === null)
        _staticWsClass = new WsClass(websocketUrl);

    return _staticWsClass ;
}

module.exports = create;

The example above works. But I have the following questions:

  1. Why is ws not undefined in the execute function (it is declared, instantiated and has scope of the subscribe function?

  2. Earlier I declared the ws (_ws) variable as a class variable of the WsClass and then I accessed the _ws variable directly in the execute function (but then I needed to re-instantiate _ws every time I experienced a close-event before calling subscribe() again). What is the most stable and correct way to structure this code (please also let me know if you have any other general thoughts about the code as well)?

Aucun commentaire:

Enregistrer un commentaire