Overview
Objectives
Understanding the basics of object-oriented programming (OOP)
How OOP relates to JavaScript
How to create constructors and object instances.
The Basics
The purpose of object-oriented programming, or OOP, is to model real world things represented in our code with objects. OOP also gives us an easy way to access code that is typically difficult or even impossible to get at.
Objects can contain the information about the thing represent, as well as the behavior you want it to have. Object functions and data are neatly stored in object packages. In programming we call this encapsulating within a namespace. This allows for better structure, access, and data storage.
Object Template
We first need to create an object template through a process called abstraction - simplifying a concept down to the most important aspects that our program can work with. Some OOP languages call this object definition a class (JavaScript doesn't); Please note this isn't actually an object, but just a template that defines characteristics. Here's a generic conceptual Person object template.
Class: Person
Object Instances
In order to give this class some data, we create object instances. Through a process known as instantiation, the class's constructor function is run and the object instance is created. Now, let's go create a person!
Object: person1
Specialist Classes
Let's say we wanted to create a more specific type of person, say a teacher or a student. OOP allows us to create these more specific child classes, teacher or student, which inherit the data from the parent class person. Let's see what these look like.
Class: Teacher
Class: Student
Notice a few things: 1. The Teacher class includes the additional property Subject. 2. Both Teacher and Student include the Greeting property, but in different ways.
Teacher has a more formal greeting, providing a prefix such as Mr., their last name, and subject they teach.
Student has an informal greeting, using the slang term "yo" and their first name.
That's the beauty of inheritance. Common features shared among child classes only need to be declared once, and can be defined separately. This ability for multiple objects to implement the same properties is known as polymorphism. You can fill in the data for these child classes the exact way we did previously.
Let's go ahead and see how to implement this example with JavaScript.
Last updated