Object Oriented Programming in JS
Object Oriented Programming in JS
In software engineering, anything that we have can be mapped to a blueprint or a vision. For
example, in Amazon, every product has a similar structure, we can generalise this and make
sure we don't repeat anything again and again.
Classes
Classes are blueprint on a set of real life entities.
Classes are going to represent how an entity should look and behave. When I say how do they
look, I refer to the properties they posses. And when I say how they behave then I mean what
actions can be performed on them.
Consider a Product class, inside this product class what do you think should be the properties
of a product ? What is a property ? Property is just any feature that the product can contain.
Every class has a name associated to it as well, that we have to define once we declare the
class.
class NameOfTheClass {
// you can details like member functions and data member
}
class Product {
name;
price;
category;
description;
rating;
addToCart() {
removeFromCart() {
displayProduct() {
console.log("Product displayed");
buyProduct() {
console.log("Product bought");
class Product {
constructor() {
// This is your custom constructor
}
}
So, to create an object we write new and then mention the name of the class followed by a pair
of parenthesis.
3. In step 3, new triggers everything need to be done for prototypes to work (will discuss
later).
4. Now, if from a constructor an object is manually returned then this manual returned object
is stored in the called variable, otherwise in any other case i.e. either we don't return
anything or return something apart from object, constructor doesn't care about it and
returns the value inside the this keyword.
this keyword of JS
this in JS works very differently than other languages.
this as a keyword is available to be accessed in any function or even outside any function,
and in classes as well.
If we can use this keyword anywhere, then what's the value stored inside this ?
let obj = {
x: 10,
y: 20,
fn: function() {
const arrow = () => {
console.log(this.x, this.y);
}
arrow();
}
}
In this code, this is present inside the arrow function, hence we will resolve it lexically.