DEV Community

Cover image for Enough JavaScript to get you Started : #13 OOP in JS Practical Guide πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»
Adarsh Pandya
Adarsh Pandya

Posted on

Enough JavaScript to get you Started : #13 OOP in JS Practical Guide πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

tutorial-cover.png

Classes and Objects

πŸ‘‰ To summarize previous article , classes are nothing but a template or blue print which decides how object will look and behave with different props/methods.

πŸ‘‰ We're Using OOP concepts because it provides us Encapsulation and Abstraction.

Enough ! Time to open VS code

GettyImages-119721301-0718585.jpg

πŸ‘‰ Start a new project , and go to app.js

πŸ‘‰ Let's make a Speedometer class

πŸ‘‰ Speedometer have properties like speed and type

πŸ‘‰ Speedometer will be having methods like increase and decrease speed

πŸ‘‰ in app.js

class Speedometer {
  speed = 0;
  type = "km/h";
  constructor(speed, type) {
    this.speed = speed;
    this.type = type;
  }
  increaseSpeed() {
    this.speed += 10;
  }
  decreaseSpeed() {
    this.speed -= 10;
  }
  getInfo() {
    console.log(this.speed);
    console.log(this.type);
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ If we decode our class there are two methods for increasing and decreasing speed of speedometer , and one method for showing information to user.

πŸ‘‰ Constructor is special function called automatically while creating object. we've used it to initialize initial speed and type of object.

πŸ‘‰ As of now class don't consume any resources but when we make objects they will surely occupy resources.

πŸ‘‰ Notice that by convention class names are always written in Pascal case

πŸ‘‰ Notice we haven't typed var or let and even function to specify in class. we don't need to specify that in class

πŸ‘‰ Currently(and even by default) we haven't specified and member access specifiers so our methods and props are accessible inside as well as outside the class.

Making Object 🌚

πŸ‘‰ Making Object of respective class simply means creating variable of that class.

πŸ‘‰ we'll use new keyword to allot resources to new object which we're creating.🏠

πŸ‘‰ The parentheses takes arguments specified in constructor parameters to initialize starter object 😁

πŸ‘‰ in app.js

var speedoMeter = new Speedmeter(0,"km/h");
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ now speedoMeter is object of class Speedometer with initial value of speed:0 and type : "km/h"

πŸ‘‰speedoMeter can now access props and methods like increase and decrease speed

πŸ‘‰ Go ahead and try calling different methods

object1.getInfo();
object1.increaseSpeed();
object1.increaseSpeed();
object1.getInfo();
object1.decreaseSpeed();
object1.getInfo();
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ this will output in console

0
km/h
20
km/h
10
km/h
Enter fullscreen mode Exit fullscreen mode

What is this?

πŸ‘‰ this keyword in JavaScript refers to current running object

πŸ‘‰ it's like we're addressing speedoMeter object with this, so this refers to the instance which is in execution now.

πŸ‘‰ in speedoMeter object we can say like this object have intial speed of 0 and type of "km/h"

πŸ‘‰ Notice if in class we want to refer the current running object (which is not there at the moment of creation of class) we'll use this to access props of current running object.

πŸ‘‰ so if we write like this.speed it will refer to speedoMeter object which we have created afterwards.

Using member access specifiers

πŸ‘‰ '#' is used to make any property or method of the class private.

πŸ‘‰ Private methods or props are only accessed inside class

πŸ‘‰ Accessing private members outside class will result in error

class Speedometer {
  #speed = 0;
  #type = "km/h";

  increaseSpeed() {
    this.#speed += 10;
  }
  #decreaseSpeed() {
    this.#speed -= 10;
  }
  getInfo() {
    console.log(this.#speed);
    console.log(this.#type);
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Notice that now if we create object of Speedometer the object can now only access increaseSpeed() and getInfo() because other members are private

console.log(object1.speed) ❌
console.log(object1.type) ❌
object1.getInfo(); βœ…
object1.increaseSpeed(); βœ…
object1.increaseSpeed(); βœ…
object1.getInfo(); βœ…
object1.decreaseSpeed(); ❌
object1.getInfo(); βœ…
Enter fullscreen mode Exit fullscreen mode

Inheritance

πŸ‘‰ Inheritance refers to deriving methods and props of parent class or super class to it's child class or sub class.

πŸ‘‰ Inheritance increases code reusability in our code

πŸ‘‰ now , think in terms of animals all animals have name and color, so what we can do is rather specifying this properties each and every time in new animal we can make a parent class with all these properties and a greet method which serves purpose of greeting.

πŸ‘‰ Syntax : class SubClass extends ParentClass that's it 😎 now we can use parent class's props and methods in child class πŸŽ‰

πŸ‘‰ Example

class Animal {
  color;
  name;

  greet() {
    console.log("hey i'm " + this.name);
    console.log("my color is " + this.color);
  }
}

class Dog extends Animal {
  constructor(name, color) {
    super();
    this.name = name;
    this.color = color;
  }
}

var dog = new Dog("tommy", "brown");
dog.greet();
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Output:

hey i'm tommy
my color is brown
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ Notice if we call constructor of sub class it's compulsory to call parent class's constructor regardless of constructor is having params or not.

πŸ‘‰ Using a reserved keyword known as super we can call parent class's constructor like => super(); or super(name,color) [if constructor is having params]

πŸ‘‰ Something looks strange? we are using color,name and greet() inside as well as outside Dog class even though these props and methods wasn't declared in Dog class.

πŸ‘‰ That's how inheritance works, it simple words it will copy all the public and protected methods and props in child class which result in code reusabilityπŸ˜€

Let me know in comment section if you have any doubt or feedback. it's always worth to give time to thriving developer community :)

Keep Coding ❀

Hey , Let' ConnectπŸ‘‹

Twitter / Github

Top comments (4)

Collapse
 
_genjudev profile image
Larson

I learned the last 10 years that many people have realy big problems with race conditions and side effects. OOP does not realy help with things except you are just good and know stuff.
Im writing functional the most time, when im writing alone. Still I need to switch to OOP for customer stuff or teams.

Maybe you write about the DANGER (monster appears here) you can easily write. The most tutorials are missing the part and don't share experience from failures. (But thats the important stuff). If you already done that sorry I missed it.

Good Work πŸ‘

Collapse
 
whoadarshpandya profile image
Adarsh Pandya

Failure is part of journey, I've covered that in one of the blogs saying it's not always sunshine. Sometimes you've to deal with errors and other stuff.

Coming to the OOP concept, even I'm using functional JS all the time. in India the major focus is given on OOP concepts, so keeping that in mind I've covered this . The reason is if someone's reading this blogs it should help them in practical work as well as interviews.

Thank you :)

Collapse
 
lathifahdhiya profile image
Lathifahdhiya

So in Java you can only have one class in each file. Is that apply to Javascript too? Also how to know if a variable/function should be public or private?

Collapse
 
whoadarshpandya profile image
Adarsh Pandya
  1. In java it's not compulsory to have one class in each file , rather it's a convetion java devs uses for SoC (separation of concern) .

  2. Same applies in JS one or more class can be defined in one file, as you can see in the example i gave in inheritance I've 2 classes in same file.

  3. Variables/Function which are public can be accessed inside as well as outside class, private members can not be accessed outside class. according to ES2015 syntax it's compulsory to prefix variable or method with '#' to make it private (which is visible difference)

Wish you all the very best for your coding career ahead :)