There are four ways to create a blueprint for Object Oriented Programming:
Constructor Syntax
Classes Syntax
OLOO
Factory Functions
Constructor Syntax
You learned the Constructor syntax in the previous lesson.
Let’s say you want to create a Human that contains a firstName and lastName. Here’s what you can write:
// Creating a Constructor
function Human (firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
You can then create an instance with the new keyword.
// Initiating an instance
const zell = new Human('Zell', 'Liew')
Class Syntax
We can create a class with the class keyword. Like constructors, we begin the class with a capital letter.
It looks like this:
class ClassName {
constructor() {
// Code to initialize instances
}
}
Everything that goes into a Constructor function would go into a class’s constructor method.
If you want to create a Human class with a firstName and lastName property, you’ll write it like this:
// Creating a Class
class Human {
constructor (firstName, lastName) {
this.firstName = firstName
this.lastName = lastName
}
}
You can then create an instance with the new keyword.
// Initializing an instance
const zell = new Human('Zell', 'Liew')
Constructors vs Classes
Constructor and Class are the same thing. Behind the scenes, JavaScript converts Classes into Constructors. That’s why people say classes are syntactic sugars.
Even though Constructors look easier to use now (since there’s less code), Classes become easier to use when Inheritance comes into play. (More on inheritance later).
OLOO Syntax
OLOO is an acronym for Objects Linking to Other Objects. This acronym is coined and made popular by Kyle Simpson.
The OLOO Syntax uses a JavaScript object as the blueprint. The most basic form of an OLOO syntax is an empty object:
const OLOO = {
// ...
}
You need a method inside the blueprint to initialise instances. This method is often called init. But it can also be called constructor, start, or whatever you want.
In init, you would write the same code as if you were writing the Constructor syntax.