views:

170

answers:

2

hi

i saw that people declare functions in two ways:

1.

application.onConnect = function(clientObj, uid,gameName) { 

   clientObj.functionname= function() { ... }

}

2.

Client.prototype.functionName = function() { ... } 

what's the difference ?

+1  A: 

The first example adds the functions to the client object that was created.

the 2nd example adds the functions to the prototype of the class that will be created when onConnect is issued.

so actually it's two ways to achieve the same results.

if i would have to guess what's faster, i would guess that using the 2nd example will be a bit faster because you add functions to the class definitions.

ufk
+2  A: 

The previous answer is incomplete.

The 1st example adds methods ONLY TO THAT SPECIFIC INSTANCE of Client class. The 2nd example adds methods to all the Class prototype.

This distinction is very important for some uses cases.

If for example the client that connects to a room has administrative privileges created by your logic, in onConnect's client instance you will add methods only to admin's user client otherwise in each admin method you will need to check if the client is admin or not (which would be ugly)

Sample:

application.isAdminUser = function(cParams) {
   if (cParams.username == 'admin') {
       return true;
   } else {
       return false;
   }
}

/* bad - people can simulate clients */
application.onConnect = function(client, cParams) {
   client.disconnectUser = function(userId) { application.myDisconnect(userId); };
   client.allClientsMethod = function() { };
}

/* good */
application.onConnect = function(client, cParams) {
   if(this.isAdminUser(cParams)) {
       client.disconnectUser = function(userId) { application.myDisconnect(userId); };
   }
   // this following is applied to all connecting clients
   client.allClientsMethod = function() { };
   // and can be done also by:
   // Client.prototype.allClientsMethod = function() { };
}

If you do not put the disonnectUser inside the if you can imagine a malicious person could forge a client that would allow him to disconnect any of your users.

I hope this helps.

iongion

related questions