2.3.1 Static Methods
In Figure 2.20, we implemented three static methods: two factory
FromBigCrunch(), and one
getter method to retrieve the total number of big bangs,
getTotalCount(). These methods are very similar to instance methods
we are already used to, with a few important differences:
- Static methods are declared with the
- In the body,
thisis bound to the class itself, rather than the instance.
- Static methods cannot call any non-static methods of the same class without first instantiating it.
The final rule above is not true when the situation is reversed. Non-static
methods can call static methods through use of the __self
object, which is a reference to the class itself. That is, this in a
static method is the same object as this.__self in a non-static
method. This is demonstrated by
To help remember __self, consider what the name states. A class is a definition used to create an object. The body of a method is a definition, which is defined on the class. Therefore, even though the body of a method may be called in the context of an instance, it is still part of the class. As such, __self refers to the class.