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:
-
Why is
wsnotundefinedin theexecutefunction (it is declared, instantiated and has scope of thesubscribefunction? -
Earlier I declared the
ws(_ws) variable as a class variable of theWsClassand then I accessed the_wsvariable directly in the execute function (but then I needed to re-instantiate_wsevery 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