Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Beginners Guide to understand the basic understanding of OOPs in Javascript.

Updated
2 min readView as Markdown
Understanding Object-Oriented Programming in JavaScript

Object oreiented programming means modelling real world things using code.

Lets take example of Car,

Behaviour of Car=start(),stop(),accelerate()

If we want to make car in a factory , we have a blueprint of a car that should behave and look.so, that we can make many cars out of it

Properties of Car=color,brand,speed

Here class is blueprint from which we can create many instance of that object means creating many objects.

What is class in javascript?

A class is a template or a blueprint that helps creating object.

class Car {
  constructor(brand, color) {
    this.brand = brand
    this.color = color
  }

  start() {
    console.log("Car started")
  }
}

Car = Class, brand,color=properties,start()=method,encapsulation is also done here were we keep data and method in a class.

Creating Objects Using Classes

Objects are created using new keywords

const car1 = new Car("Toyota", "Red")
const car2 = new Car("BMW", "Black")

//car1.brand -> Toyota
//car2.color -> Black
//car1.start()-> Car Started

car1 and car2 are two new objects,each objecthas its own data.

Example that will us to understand more

class Student {
  constructor(name, age) {
    this.name = name
    this.age = age
  }

  printDetails() {
    console.log(this.name + " is " + this.age + " years old")
  }
}
//creating new objects
const s1 = new Student("Aman", 20)
const s2 = new Student("Priya", 21)

//calling Methods inside a class that is encapsulated
s1.printDetails() //Aman is 20 years old
s2.printDetails()//Priya is 21 years old

I hope this gives you basic understanding of oops inside javascript.

1 views