[Cosmo-dev] How we declare (pseudo) Classes in JavaScript

Bobby Rullo br at osafoundation.org
Tue Sep 18 11:48:36 PDT 2007


As we all know, there are lots of ways to declare a class, pseudo  
class, prototype, constructor whatever you want to call it.

I'd like to propose that we settle on one way, namely:

> dojo.declare("NewClassName", OldClass, {
>    initializer: function (){ ... }
>
>     //other declarations to be mixed in
> }

The other way which is prevalent in our code is:

>
>
> cosmo.foo.NewClass = function() {
>     ...stuff...
> }
>
> cosmo.foo.NewClass.prototype = new cosmo.foo.OldClass();

Basically, you are create a function to be used as a constructor then  
assigning it a prototype post-facto. I prefer the first way because:

	* you can see in the first line that NewClass descends from OldClass

	* There's less typing

	* The second way forces you to put all declarations in the  
constructor function (which is wasteful since functions will get re- 
declared on every instantiation), or else put the stuff in the  
prototype AFTER the the ancestor prototype is assigned, further  
obfuscating the ancestor. So if you wanted to put something on your  
prototype, you'd end up with something like this:


> cosmo.foo.NewClass = function() {
>     ...stuff...
> }
>
> cosmo.foo.NewClass.prototype = new cosmo.foo.OldClass();
>
> cosmo.foo.NewClass.prototype.a = function(){
> }
>
> cosmo.foo.NewClass.prototype.b = function(){
> }

See how "OldClass" gets buried in the middle?

Dojo provides us with a nice solution to the manual labors of  
inheritance, I think we should standardize on it.

Bobby


More information about the cosmo-dev mailing list