views:

28

answers:

1

Forgive my probably incorrect application of terminology in this question (btw, please correct me where wrong).

Let's say we have a custom object we want to define. Some of the methods on this object make sense to be 'instance' specific. And we also have some methods that are really independent of the instance, sort of like a public static method in a language like C# or Java.

What is the standard practice for creating these functional definitions? Currently, I am doing something like this:

var User = function(name){
  this.Name = name;
  User.instances.push(this);
};

User.instances = [];
User.doSomething = function(){
  // do something interesting with the set of user instances
};

var me = new User('me');
var you = new User('you');
User.instances; // => [me, you]

Notice how the 'static' methods get defined in a completely different section from the prototype/instance methods. They just don't feel connected looking at the code. In my ideal world, I would be able to define everything together (perhaps inside the User = function(){}?), to keep the code a little cleaner and connected. I understand one of the powers of JS is you can do things separate and modify on the fly. Just curious what the standard practice is on something like this.

Sometimes I just nest the 'static' definitions in some brackets - even though the brackets are actually syntactically meaningless:

// Static definitions
{
    User.instances = [];
    User.doSomething = function(){
      // do something interesting with the set of user instances
    };
}

Is there a standard practice that I am unaware of?

+1  A: 

Your approach is perfectly fine, although you can - if you really insist - try to do wacky tricks like assigning these static attributes inside a constructor conditionally based on whether they were already assigned.

IMHO this will not make it more readable but will have worse performing code due to the test (if you create lots of these User objects)

DVK
The aim is for readability here, so I think I'll avoid the wackiness :) Thanks.
Matt