Static/class methods
Static methods (also known as class methods) are methods that you call on classes themselves,
rather than their instances. To add static methods to your class, wrap them up in an extend block:
var User = new JS.Class({
extend: {
find: function(id) {
// Return a User with id
},
create: function(name) {
return new this(name);
}
},
initialize: function(name) {
this.username = name;
}
});
Note that extend (as defined above) will not become an instance method of the class. Within
static methods, this refers to the class itself – see the create() method.
var james = User.create('James');
james.username // -> 'James'
james.klass // -> User
When you create a subclass, it will inherit any static methods of its parent, and you can use
callSuper() too:
var LoudUser = new JS.Class(User, {
extend: {
create: function(name) {
return this.callSuper(name.toUpperCase());
}
}
});
var me = LoudUser.create('James');
me.username // -> 'JAMES'
me.klass // -> LoudUser
var you = LoudUser.find(24) // inherited from User
Note how this, even in callSuper methods, always refers to the same thing as in the original
method call. We get back a LoudUser, not a User.