Classes and Instances
JavaScript is flexible to a fault. It can be whatever you need it to be (object-oriented, functional, procedural, imperative, declarative, event-driven, etc).
Plain Object Oriented Programing (also, don’t abbreviate) was always possible with JavaScript but Modern JavaScript also added support for the Class syntax.
A class is the concept for a template or blueprint for you to define shared structure and behavior among similar objects. You can define new classes, make them extend other classes, and instantiate objects out of them using the new keyword. You can customize the construction of every object and define shared functions between these objects. Most importantly, you can do all that without bothering to understand the concept of prototype-based delegation!
You can tell I am not a fan of Classes. In fact, I get so much pleasure in removing them from code. It’s why I am a big fan of the upcoming React Hooks.
You’ll find classes in many projects and examples and to be fair, some of their usage is actually not bad. You, on the other hand, should only use them when you fully understand why you think you need them.
Here’s a standard class example that demonstrates the magical things you can do with classes:
class Person { constructor(name) { this.name = name; } greet() { console.log(Hello ${this.name}!
); } } class Student extends Person { constructor(name, level) { super(name); this.level = level; } greet() { console.log(Hello ${this.name} from ${this.level}!
); } } const o1 = new Person('Max'); const o2 = new Student('Tina', '1st Grade'); const o3 = new Student('Mary', '2nd Grade'); o3.greet = () => console.log('I am special!'); o1.greet(); // Hello Max! o2.greet(); // Hello Tina from 1st Grade! o3.greet(); // I am special!
In this example, you have a Person
class and a Student
class that extends the Person
class, because every student is a person, d’oh!.
Both classes define a constructor
function. The constructor
function is a special one that gets called every time you instantiate an object out of the class, which you do using the new
keyword (used above to instantiate o1
, o2
, o3
).
The arguments you pass to the new
call are accessible in the constructor
function of the class. The Person
class expects a name
argument and it stores that value on the instance using the this
keyword. The Student
class expects a name
and a level
arguments. It stores the level
value on its instance and since it extends the Person
class it can call the super
method with the name
argument, which will invoke the Person
class constructor
function and store the name
as well. Both classes define a greet
function that uses the values they store on each instance. A greet
method was also directly defined on o3
.
When all 3 greet
methods are invoked, o1
will use the method from its class, the Person
class, o2
will use the method from the Student
class, and o3 will use its own directly defined method.