Table of contents
Before diving deep into javascript OOP, what is OOP?, OOP is all about modeling a system as a collection of objects.
Javascript is not a class-based object-oriented language, it is a prototype-based language. The features of OOP can be found in my LinkedIn post URL below
When creating classes in javascript OOP, we use the class
keyword which is an ECMAScript 6 (ES6) syntax.
For example:
class Car{
/* We decalare a class called Car */
}
In javascript classes, we have properties and methods. In procedural programming, it is called variables and functions respectively.
class Car{
/* We decalare a class called Car */
tyres; // this is a property
sidemirror; // this is a property
engine; // this is a property
accelerate(){
// this is method
// the contents of the accelerate() method runs immediately it is called
}
decelerate(){
// this is method
// the contents of the accelerate() method runs immediately it is called
}
}
Constructor
Some javascript newbie developers become overwhelmed when they encounter the constructor()
method for the first time.
The constructor()
is simply a special method that creates and initializes an object instance of a class. Still sounds strange, right?
The constructor()
gets invoked when an object is created with the new
keyword.
Therefore the new
keyword ensures that the constructor()
method is invoked.
Let's jump to the code:
class Car{
/* We decalare a class called Car */
// declaring the properties here could be ommited
// since constructor() method will create all the properties before initializing them.
tyres; // this is a property
sidemirror; // this is a property
engine; // this is a property
// Listing out properties is a good pratice although it could be ommited as well
// constructor() method
constructor(tyres, sidemirror, engine){
this.tyres = tyres
this.sidemirror = sidemirror
this.engine = engine
}
accelerate(){
// this is method
// the contents of the accelerate() method runs immediately it is called
}
}
In the code snippet above, I made use of the this
keyword.
Let's take a brief look at what the this
keyword does.
The this
keyword refers to the object itself, which is Car
object.
Therefore any property that gets bonded to a this
keyword is accessible globally in the class.
Let's jump to code once again:
class Car{
/* We decalare a class: Car */
// create a property: speed
// and initialize it with a default value of: 30
// speed; - omitted
// constructor() method will create the speed property before initializing it.
constructor(speed){
this.speed = speed
}
accelerate(){
// increases the object
this.speed += 20
}
emitSpeedValue(){
return this.speed
}
}
let ford = new Car(20)
console.log(ford.speed) // 20
ford.accelerate()
console.log(ford.speed) // 40
It is also not mandatory for you to create a constructor()
method on every class, you could omit it. But there would be no personalization of any objects created from that blueprint or class.