The main thing that classes give you, other than that they're nice to use, is private and static fields. You might be able to achieve this with some bastard arrangement of global variables, or define them in a closure somewhere so that they're not accessible to the outside, but classes will just package them in naturally.
A private field is only accessible within class methods, e.g. you could do:
JavaScript:
class MyClass {
#privateValue;
getValue() {
return this.#privateValue;
}
setValue(val) {
this.#privateValue = val;
}
}
Obviously this isn't a particularly useful example, but now any
MyClass
object will have get/set functions that access the private
#privateValue
field that won't be accessible outside otherwise. You could use private fields to store aspects of the object's internal state in a way that wouldn't be meaningful to the outside, or you can use private fields which are methods to perform internal stuff that you'll only need to call from other class methods.
Static fields are global to the class, so if
MyClass
had a defined
static #staticValue;
then any class method could access
MyClass.#staticValue
, but only class methods could access it. Note that any
instance of the class could access the static value, and it'd be the same value. You could do something like have the class keep track of how many instances of it have been created (or are "active").