Appitizer...
Static methods in JavaScript are properties of the Object which references them. They are not added to the prototype of the Object.
There are two ways to add a function to an object in JavaScript. Below, I am adding methods to an imaginary object called, "MyObject
".
Property
MyObject.staticMethod = new function() {};
MyObject.staticMethod(); // Call static method.
Method
MyObject.prototype.instanceMethod = new function() {};
new MyObject().instanceMethod(); // Call instance method.
Main Course...
There are three (3) ways to add static methods to a class. The code below is derived from "Pro JavaScript with MooTools" by Mark Obcena.
I included some more information which was lacking from Arcabard's answer.
1. As an Object property
var Person = new Class({
// Instance Variables
name: '',
age: 0,
// Constructor
initialize: function(name, age) {
this.name = name;
this.age = age;
},
// Instance Methods
log: function() {
console.log(this.name + ', ' + this.age);
}
});
// Static Property
Person.count: 0;
// Static Methods
Person.addPerson: function() {
this.count += 1;
};
Person.getCount: function() {
console.log('Person count : ' + this.count);
};
2. Using the extend()
var Person = new Class({
// Instance Variables
name: '',
age: 0,
// Constructor
initialize: function(name, age) {
this.name = name;
this.age = age;
},
// Instance Methods
log: function() {
console.log(this.name + ', ' + this.age);
}
});
Person.extend({
// Static Property
count: 0,
// Static Methods
addPerson: function() {
this.count += 1;
},
getCount: function() {
console.log('Person count : ' + this.count);
}
});
3. Adding a new mutator to Class.Mutators
// This will create a shortcut for `extend()`.
Class.Mutators.Static = function(members) {
this.extend(members);
};
var Person = new Class({
Static: {
// Static Property
count: 0,
// Static Method
addPerson: function() {
this.count += 1;
},
getCount: function() {
console.log('Person count : ' + this.count);
}
},
// Instance Variables
name: '',
age: 0,
// Constructor
initialize: function(name, age) {
this.name = name;
this.age = age;
},
// Instance Methods
log: function() {
console.log(this.name + ', ' + this.age);
}
});
Example using the static methods.
// Creating a new Person instance
var mark = new Person('Mark', 23);
mark.log();
// Accessing the static method
Person.addPerson();
Person.getCount() // 'Person count: 1'