When you assign a property to an object, the key for the property is a string. If you pass something like a socket as the key, then javascript will endeavor to convert it to a string and store that as a key. If the WebSocket has no special support for the toString()
method which does the conversion to a string, then you will get some generic conversion such as [object Object]
which will mean that all your WebSockets will appear as the same property.
The same is true for .hasOwnProperty()
when you go to look up the key. So, you will essentially be doing:
theObject.hasOwnProperty("[object Object]")
for all your sockets and thus they will all look the same.
You can work around it by giving your sockets some sort of unique ID and then using that as the key and you can put the socket itself as the data in your map object.
For example, you could do this:
function addSocketToMap(socket, obj) {
if (!socket.uniqueKey) {
socket.uniqueKey = addSocketToMap.cntr++;
}
obj[socket.uniqueKey] = socket;
}
addSocketToMap.cntr = 0;
function isSocketInMap(socket, obj) {
if (socket.uniqueKey) {
return obj.hasOwnProperty(socket.uniqueKey);
}
return false;
}
var theObject = {};
addSocketToMap(socketA, theObject);
addSocketToMap(socketB, theObject);
var a = isSocketInMap(socketA, theObject); // true
var b = isSocketInMap(socketB, theObject); // true
You could also probably just override toString for the WebSocket object if this doesn't cause any problems with its implementation:
(function() {
var cntr = 0;
WebSocket.prototype.toString = function () {
// add a uniqueKey if it doesn't already exist
if (!this.uniqueKey) {
this.uniqueKey = cntr++;
}
// make a unique string identifier
// that will look like "WebSocket_xxx"
return "WebSocket_" + this.uniqueKey;
}
})();