DEV Community

Cybermaxi7
Cybermaxi7

Posted on

Object Oriented Programming in Javascript!🤔

WHAT IS OBJECT ORIENTED PROGRAMMING?🤔

Object oriented programming (OOP) is a programming paradigm(style of code, how we write and organize code) based on the concept of objects.
We can use objects to model (describe) real world or abstract features
Objects may contain data(properties) and code (methods). By using objects, we pack data and the corresponding behavior into one block

code example

const user = {
    user: 'cyber',
    password: '12345',

    login(password) {
        //Login Logic
    }
    sendMessage(str) {
        //sending Logic
    }
 }
Enter fullscreen mode Exit fullscreen mode

In the above code, user is the object used to model a real life user, in it contains the user's name and password, this is the DATA
However the two functions contained in the user's object is the behavior of that object.

In OOP, objects are self-contained pieces/blocks of code
They are also building blocks of application and they interact with one another. This interaction happens through a public interface(API): methods that the code outside of an object can access and use to communicate with the object

WHY DOES OOP ACTUALLY EXIST? 🤷‍♂️

OOP was developed with the goal of organizing code, to make it more flexible and easier to maintain (avoid "spaghetti code" 🍝

THE FOUR(4) FUNDAMENTAL OOP PRINCIPLES

✅ Abstraction
✅ Encapsulation
✅ Inheritance
✅ Polymorphism

ABSTRACTION

Abstraction is ignoring or hiding details that don'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

ENCAPSULATION

Encapsulation simply means keeping properties and methods private inside class, so they are not accessible from the outside class however some methods can be exposed as a public interface (API). this is why we said earlier that interactions between objects happen through a public interface

INHERITANCE

Inheritance is making all properties and methods of a certain class available to a child class, forming a hierarchical relationship between classes. this allows us to reuse common logic and modern real world relationships

POLYMORPHISM

Polymorphism simply means a child can OVERWRITE a method it inherited from a parent class

OOP IN JAVASCRIPT (PROTOTYPES)

Objects are linked to a prototype object,The prototype contains methods (behavior) that are accessible to all objects linked to that prototype. this concept is known is prototypal inheritance

Example: Array

const num = [1, 2, 3, 4]
num.map(v => v * 2);

Enter fullscreen mode Exit fullscreen mode
The above code shows the use case for the map method. checking the **MDN web docs**, we find out that the name of the map method is actually _**Array.prototype.map()**_.
Array.prototype is the prototype of all array objects we create in JavaScript. when we call an array with this map method, all methods associated with the map is been accessible by our array. 
Enter fullscreen mode Exit fullscreen mode

WAYS OF IMPLEMENTING PROTOTYPAL INHERITANCE IN JAVASCRIPT

the following questions might come into your minds
how do we actually create prototypes? 🤷‍♂️
how do we link objects to prototypes? 🤷‍♂️
how can we create new objects without having classes? 🤷‍♂️

*Three ways actually..
*

1. CONSTRUCTOR FUNCTIONS

This is a technique to create objects from a function, it is how built-in objects like Arrays, Maps, or Sets are actually implemented
Code example

const Person = function (firstName, birthYear) {
  this.firstName = firstName,
 this.birthYear = birthYear;
// Adding method
// Never create a method in a constructor function like this
this.calcAge = function() {
  console.log(2023 - this.birthYear);
}
};
const cyber = new Person('cybermaxi', 1990);
console.log(cyber);
// Rather create methods like this
Person.prototype.calcAge = function() {
  console.log(2023 - this.birthYear);
}
cyber.calcAge()
1. a new object / {} is created
2. the function is called, this = object / {}
3. the object / {} is linked to the prototype
4. the function automatically returns an object / {}

Enter fullscreen mode Exit fullscreen mode

2. ES6 CLASSES

Modern alternative to constructor function syntax

** Syntactic sugar**
: behind the scenes, ES6 classes work exactly like constructor function
ES6 classes do not behave like classes in "Classical OOP "

class PersonCl {
  constructor (firstName, birthYear) {
    this.firstName = firstName,
    this.birthYear = birthYear

  }

  calcAge = function() {
    console.log(2023 - this.birthYear)
  }
} 
const cyber = new PersonCl('cybermaxi', 1990)
cyber.calcAge()
Enter fullscreen mode Exit fullscreen mode

Note

  1. Classes are not hoisted(cannot be used before declaration)
  2. Classes are first class citizens just like functions(can be passed into functions and returned from a function)
  3. classes are executed in strict mode

one advantage of classes over constructors is that it keeps all the code(that is the variables and behaviors) nice and clean in one block

3. OBJECT.CREATE()

This is the easiest and most straightforward way of linking an object to a prototype object

NB. Javascript doesn't have classes therefore constructors have been used since the beginning to try to emulate classes

const PersonProto = {
  birthYear: 2000,
  name: 'Caleb',
  calcAge() {
    console.log(2023 - this.birthYear);
  }
}
const caleb = Object.create(PersonProto);
// caleb.name = 'Caleb'
// caleb.birthYear = 2000
caleb.calcAge()
Enter fullscreen mode Exit fullscreen mode

I hope you found this helpful 😊

Cybermaxi7 💗
Jonas Schmeddtmann JavaScript course ❤️

Top comments (2)

Collapse
 
corners2wall profile image
Corners 2 Wall

Keep going ⇗

Collapse
 
cybermaxi7 profile image
Cybermaxi7

Thank you 🙏🏽❤️