Object Oriented Programming in JavaScript
In this tutorial, we will learn about the OOPS concept in JavaScript.
What is OOPS in JavaScript?
OOP is a programming paradigm based on the concept of objects.
Paradigm simply means the style of the code, how we write and organize code.
OOP is the most widely used programming paradigm in large scale software engineering .
What is Class?
Class is Like a blueprint from which we can create new objects based on the rules described in the class
What is Object?
The Objects are self-contained pieces/blocks of code.
Why OOP?
The Object-Orient Paradigm was introduced to organizing code, and make it more flexible and easier to maintain
The 4 fundamental principle of OOPS
There are four fundamental principals that can used while creating class, which are Abstraction, Encapsulation, Inheritance, and Polymorphism.
Abstraction:
Abstraction means Ignoring or hiding details that won't matter, allowing us to get an overview perspective of the thing we're implementing, instead of messing with details that don't really matter to our implementation.
Let's say we'ew implmeting a phone for a user to use, they don't need to know whtas going on inside phone, he have to use phone only
Encapsulation
The Encapsulation Basically means keeping properties and methods private inside the class, so they are not accessible from the outside the class.
That Prevents external code from accidentally manipulating internal properties or state
Inheritance
Child class extends parent class
Making all properties and methods of a certain class available to a child class, forming a hierarchical relationship between classes.
Goal is to reuse logic that is common to both of the classes.
Polymorphism
A child class can overwrire a method it inherited from a parent class
in simple child class can overwrite a method that is inherited from a parent class
OOPS in JavaScript
Objects (instances) are instantiated from a class, which functions like a blueprint, this process of creating an instance is called instantiation
Prototype
Objects are linked to a certain prototype object, so we say that each object has a prototype
In javscript we have something called prototypes and all objects in javascript are linked to a certain prototype object, so we can say that each object has a protptype
the prototype object contains methods and properties that all the objects that are linked to that property can access and use. and this behavior us usually called prototype inheritance.
so, the prototypal inheritance means that all objects that are linked to a certain prototype object can use the methods and properties that are defined on that prototype
so basically, object inherit methods and properties from the prototype which is the reason why this mechanism is called prototype inheritance
3 ways of imlemmeting prototypal inheriance in js
1) Constructor functions
2) ES6 class
3) Object.create()