Skip to content

March 2, 2011

Dojo Classes, Inherited and Constructors

Dojo provides the ability for developers to create Java-like classes with the powerful dojo.declare(). It does this by allowing you to easily create namespaced classes that support multiple inheritance (which are basically mixins). Provided in this functionality is the ability to call:

this.inherited(arguments);

… from within any of your methods in a class that extends another and have it call the super class instance of that method in the same way you would call super() in a Java class to call the super class’ method.

This past week I was on a couple of new classes, one super class and another class that extends that super class. I called this.inherited() within my constructor of the class to call the super constructor. I was noticing something strange in Firebug though—my super class’ constructor was getting called twice even though I was only calling it once. I reproduced this in JSFiddle as you can see below:

If you had FireBug (or JavaScript console in WebKit) open you would have seen that the super constructor was getting called twice. After pinging #dojo on irc at irc.freenode.net about the issue, @phiggins reminded me that when you instantiate classes that extend other classes, the constructor method automatically calls the super on its own. So if you call it again, it will be called twice. You can read about the default constructor chaining that dojo.declare gives you on the Reference Guide.

To summarize, only use this.inherited() within non-constructor methods in your classes. I recall running into this issue once before so I thought I blog about it for my own personal reference and for that of others.

Share your thoughts, post a comment.

(required)
(required)

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments