I would like to know what is the correct way to pass the reference of the io variable to a class in Node.js
I currently have the variable initialized in a file index.js
:
const io = require('socket.io').listen(9000)
Reading some blogs I have observed that they only pass the variable to the constructor in this way:
class Foo{
constructor(io){
this.io = io
}
}
let objFoo = new Foo(io)
However, io contains inside an object with the active sockets, the question is: Will io
the class attribute contain the connections (active sockets) that are made after the instantiation of it? if not, is there any other way to reference the io variable from another .js document (because the class is in another doc)?
You could make a file where you raise the socket with io and export that variable:
It would be something like this: socket.js
And where you want to use it would be something like: file.js
Remember that, in Javascript, Objects (non - primitive data ) are passed by reference .
That means you're actually using the exact same object everywhere. Even if you copy it (as you indicate in your example), in reality you will still use the same object , albeit with several different names.
In short: yes , it will contain whatever the original object contains, since it is the same. Even if it is added after copying it.