Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Updated
4 min readView as Markdown

Classes are a extensible programming template for creating objects, providing initial values for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions or methods).

class User {
  constructor(name){
   this.name = name;
  }
  sayHi(){
   console.log(this.name);
  }
} 
let user = new User("Ram");
user.sayHi();

console.log(typeof User);
console.log(User === User.prototype.constructor);
console.log(User.prototype.sayHi);
console.log(Object.getOwnPropertyNames(User.prototype));
// Output
//function
//true
//[Function: sayHi]
//[ 'constructor', 'sayHi' ]

Classes are just like syntactic sugar and its datatype is function. Constructor is a special method used to create and initialize an object instance of class.

Method is a function that belongs to an object or a class.

What class User {...} construct really does is:

  1. Creates function named User , that become result of class declaration. The function code is taken from the constructor method (assumed empty if we don't write such method).

  2. Stores class methods , such as sayHi , in User.prototype.

The New () keyword

The new keyword is used to create an instance of an object that has a constructor function.

function tvs(chasisnumber , modelName){
  this.chasisnumber = chasisnumber;
  this.modelName = modelName;
  this.fuelLevel = 100;
}

tvs.prototype.status = function() {
  return `TVS \({this.modelName} # \){this.chasisnumber} fuel : ${this.fuelLevel}`;
}

const car1 = new tvs("MH-101", "hdbqjwbj");
const car2 = new tvs("RH-156", "dbqwhjbh");
console.log(car1.modelName);
console.log(car1.status());
console.log(car2.modelName);
console.log(car2.status());

// output
// hdbqjwbj
// TVS hdbqjwbj # MH-101 fuel : 100
// dbqwhjbh
// TVS dbqwhjbh # RH-156 fuel : 100

Step 1- When we use new keyword , an empty object is created.

Step 2- Then , prototype of empty object with prototype of tvs is linked.

Step 3- Now , this word is activated. It will bind with who is calling it. Ex - value provided while creating car1 is bind with the this keyword.

Step 4- If constructor does not return explicitly , then new keyword automatically return.

Note:- New keyword create new instances.

Prototype

Every object has an internal link to another object is called prototype and important use is inheritance. The prototype is itself an object, so the prototype will have its own prototype will have its own prototype , that is called prototype chain. The chain ends when we reach a prototype that has null for its own prototype.

This is an object called Object.prototype and it is the most basic prototype, that all objects have by deault. The prototype of Object.prototype is null, so it is the end of prototype chain.

Object.getPrototypeOf(myObject); // Object { }

We use Object.create() method to create new object with specified prototype object and optional properties.

Inheritance

It is a way for one class to extend another class.

class Animal{
  constructor(name){
    this.name = name;
  }
  run(speed){
    this.speed = speed;
    console.log(`\({this.name} runs with speed \){this.speed}`);
  }
}

let animal = new Animal("animal1");

class Rabbit extends Animal{
  hides(){
   console.log(`${this.name} hides`);
  }
}

let rabbit = new Rabbit("white rabbit");
rabbit.run(5);
rabbit.hide();

//white rabbit runs with speed 5
//white rabbit hides

Object of Rabbit class have access both to Rabbit methods, such as rabbit.hide(), and also to Animal methods, such as rabbit.run().

Encapsulation

It is defined as wrapping up data and information under a single unit. In OOP, encapsulation is defined as binding together the data and functions that manipulate them together in a class.

class BankAccount {
  #balance;
  constructor(owner, initialDeposit) {
    this.owner = owner;
    this.#balance = initialDeposit;
  }

  // Public method to check balance (Getter)
  getBalance() {
    return `Account owner: \({this.owner}. Balance: \){this.#balance}`;
  }

  // Public method to modify private data (Setter/Action)
  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
      console.log(`Deposited ${amount}.`);
    }
  }
}

const myAccount = new BankAccount("Alice", 1000);

myAccount.deposit(500); 
console.log(myAccount.getBalance()); 
// "Account owner: Alice. Balance: $1500"

// Attempting to access private data directly:
// console.log(myAccount.#balance); 
// SyntaxError: Private field '_balance' must be declared in an enclosing class