Static Members
Video Lecture
Section | Video Links |
---|---|
Static Members |
Overview
All the parts of a class, such as the properties, constructor and methods are called members. When you instantiate a class, e.g,
const CAT = new Cat()
You are creating a new object in memory with its own copies of all the members of the Cat
class.
E.g, I can create two independent objects using the Cat
class.
const CAT1 = new Cat()
const CAT2 = new Cat()
They would then have their own copies of the members independently of each other. So, if the Cat
class described a name
property and/or walk
method, then calling CAT1's
properties, constructor and methods would return a different result than calling CAT2's
properties, constructor and methods. Both objects are independent in memory but were both created from the same class template.
Now it's possible to make objects that were instantiated from classes share the same methods and properties behind the scenes, and that is using the static
keyword.
The code below shows some examples of the static
keyword and how the static
properties and methods are referred to.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
Outputs
123
123
123
123
In the above example, note that CLASS_B
and CLASS_D
were not actually needed at all to be instantiated to access their static members. They were not used, and I could have just commented them out completely. Static members are referred to directly by the classes name instead.
console.log(ClassWithStaticProperty.abc)
console.log(ClassWithStaticMethod.method())
One particular example where a static property may be useful is in the example below where the property PI
doesn't need to be recreated across each new instance of the Circle
class, but all instances of the circle
can point to the same value stored at the class level instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
Outputs
Circle.PI = 3.14
CIRCLE1 Area = 3.14
CIRCLE2 Area = 12.56
CIRCLE3 Area = 28.26
In the above example, each new instance of Circle
referred to the static property of Circle.PI
in the calculation.
Note that if using PI in your code, it is less work to use the inbuilt JavaScript static Math
object instead.
E.g,
console.log('CIRCLE1 Area = ' + Math.PI * CIRCLE1.radius ** 2)
Visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math for more information about the Math
object.