You are on page 1of 2

The difference between STATIC methods and OBJECT methods

Below is a class in which .do is a normal class method…


class Demo {
do () {
console.log('this does something in the object')
}
}

Trying to run / invoke the method from the Class fails.


Demo.do()

VM149:1 Uncaught TypeError: Demo.do is not a function

Creating an object first is needed to execute the method.


aDemo = new Demo() // create an object
aDemo.do() // execute the method from the object
'this does something in the object'

You should use class methods MOST of the time. Object each have different data / state and should
each behave differently.
Sometimes you have something that is always true (‘invariant’), in which case you need a class
method.

For example, the value of PI never changes

So PI exists on the Math CLASS and no object is needed to access it.


Math.PI
3.141592653589793

Below is a class with a static method


class Demo2 {
static do () {
console.log('this is a static method')}
}

The method is ‘invoked’ from the class…


Demo2.do()
'this is a static method'

Trying to access the method from an object results in an error message.


aDemo2 = new Demo2()
aDemo2.do()

Uncaught TypeError: aDemo2.do is not a function

A good use of a static class method is to setup the data in a Controller class
class Controller {
static setup () {

Controller.setup should create and return the main / root class for a system.

You might also like