Best practices for static methods and variables with MooTools classes
Caveat: Never used MooTools. I've used Prototype a fair bit, though, which has a similar Class
system (MooTools is either "inspired by" or a fork of Prototype, depending on who you ask).
Just add them as properties on the resulting "class":
var MyClass = new Class(properties);
MyClass.staticMethod = function() {
// ...
};
(The first line above is from the docs; the remainder is my addition.)
You know that will happen prior to initialize
on any new instance because you're not leaving an opportunity for creating a new instance prior to attaching your static methods (or properties).
I know this post is old, but I wanted to give a better answer than was already stated.
I recommend the following syntax for static methods:
var MyClass = new Class({
initialize: function() {
this.method();
MyClass.staticMethod();
}
,
method: function() {}
}).extend({
staticMethod: function() {}
});
The .extend({})
method is the standard way to add static methods on a Class.
The only thing I don't like is the MyClass.staticMethod();
syntax, but there aren't many better options.