JavaScript Class-Based Object-Oriented Programming (OOP)

Classes and instances

When we model a problem in terms of objects in OOP, we create abstract definitions representing the types of objects we want to have in our system. For example, if we were modeling a school, we might want to have objects representing professors. Every professor has some properties in common: they all have a name and a subject that they teach. Additionally, every professor can do certain things: they can all grade a paper and they can introduce themselves to their students at the start of the year, for example.

So Professor could be a class in our system. The definition of the class lists the data and methods that every professor has.

In pseudocode, a Professor class could be written like this:

class Professor
    properties
        name
        teaches
    methods
        grade(paper)
        introduceSelf()

This defines a Professor class with:

  • two data properties: name and teaches
  • two methods: grade() to grade a paper and introduceSelf() to introduce themselves.

On its own, a class doesn't do anything: it's a kind of template for creating concrete objects of that type. Each concrete professor we create is called an instance of the Professor class. The process of creating an instance is performed by a special function called a constructor. We pass values to the constructor for any internal state that we want to initialize in the new instance.

Generally, the constructor is written out as part of the class definition, and it usually has the same name as the class itself:

class Professor
    properties
        name
        teaches
    constructor
        Professor(name, teaches)
    methods
        grade(paper)
        introduceSelf()

This constructor takes two parameters, so we can initialize the name and teaches properties when we create a new concrete professor.

Now that we have a constructor, we can create some professors. Programming languages often use the keyword new to signal that a constructor is being called.

walsh = new Professor("Walsh", "Psychology");
lillian = new Professor("Lillian", "Poetry");

walsh.teaches; // 'Psychology'
walsh.introduceSelf(); // 'My name is Professor Walsh and I will be your Psychology professor.'

lillian.teaches; // 'Poetry'
lillian.introduceSelf(); // 'My name is Professor Lillian and I will be your Poetry professor.'

This creates two objects, both instances of the Professor class.