DEV Community

Cover image for Object Oriented Programming With JavaScript - Part 1 🚀
Ali Samir
Ali Samir

Posted on • Updated on

Object Oriented Programming With JavaScript - Part 1 🚀

JavaScript fundamentally adopts Object-Oriented Programming (OOP) principles.

OOP, a programming paradigm, revolves around representing real-world entities as objects, facilitating superior code organization, reusability, and maintainability.

Let's explore how JavaScript embodies OOP via its object-oriented functionalities.


đź“Ś An Introduction to Objects

Objects serve as the cornerstone of JavaScript. They represent collections of key-value pairs, accommodating values of diverse data types, such as other objects or functions. One of their key features is their dynamic nature, enabling properties and methods to be manipulated—added, altered, or deleted—during runtime.

In JavaScript, declaring an object is straightforward through object literal notation, exemplified as follows:

let car = {
    brand: 'Toyota',
    model: 'Corolla',
    year: 2022,
    start: function() {
        return `${this.brand} ${this.model} started!`;
    }
};
Enter fullscreen mode Exit fullscreen mode

Or by using the object constructor function:

let person = new Object();

person.name = 'John';
person.age = 30;
person.greet = function() {
    return `Hello, my name is ${this.name}.`;
};
Enter fullscreen mode Exit fullscreen mode

Accessing Object Properties and Methods

To access properties and methods within an object, we can use dot notation or bracket notation, like so:

console.log(car.brand); // Dot notation to access property
console.log(car['model']); // Bracket notation to access property

console.log(car.start()); // Accessing object method
Enter fullscreen mode Exit fullscreen mode

Quite straightforward, isn't it? However, what's the process for incorporating or altering these attributes?

car.color = 'blue'; // Adding a new property
car.year = 2023; // Modifying an existing property
delete car.model; // Removing a property
Enter fullscreen mode Exit fullscreen mode

Object Prototypes and Inheritance

The distinctive aspect of JavaScript lies in its prototypal inheritance system.

In JavaScript, each object possesses a prototype, from which it inherits both properties and methods. Delving deeper into this concept is our aim below.

Example of an object:

// Creating an object
let car = {
    brand: 'Toyota',
    model: 'Corolla',
    year: 2022,
    start: function() {
        return `${this.brand} ${this.model} started!`;
    }
};

// Accessing object properties
console.log(car.brand); // Output: Toyota

// Accessing object method
console.log(car.start()); // Output: Toyota Corolla started!
Enter fullscreen mode Exit fullscreen mode

đź”° Prototypal Inheritance

In JavaScript, prototypal inheritance facilitates object inheritance. Every object in JavaScript possesses a prototype. When a property or method is accessed on an object, JavaScript initially searches for it directly within the object. If it's not found, it traverses through the object's prototype chain until the property or method is encountered, or until the chain ends at null.


Prototype Property

Each JavaScript function possesses a prototype property, initially an empty object. When a function serves as a constructor to instantiate objects via the new keyword, the prototype property of that function becomes the prototype of the freshly generated object.

An example:

// Creating a constructor function
function Vehicle(brand, model, year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
}

// Adding a method to the prototype of Vehicle
Vehicle.prototype.start = function() {
    return `${this.brand} ${this.model} started!`;
};

// Creating an instance of Vehicle
let car = new Vehicle('Toyota', 'Corolla', 2022);

console.log(car.start()); // Output: Toyota Corolla started!
Enter fullscreen mode Exit fullscreen mode

In the example mentioned earlier, 'Vehicle' functions as a constructor. By adding the start method to the Vehicle.prototype, it becomes accessible to all instances generated by invoking 'new Vehicle()'.


Inheritance through Prototypes

Prototypal inheritance enables objects to acquire properties and methods from their prototypes. When an object is instantiated through a constructor function, it automatically inherits properties and methods from the constructor's prototype.

Example:

function Vehicle(brand, model, year) {
    this.brand = brand;
    this.model = model;
    this.year = year;
}

Vehicle.prototype.start = function() {
    return `${this.brand} ${this.model} started!`;
};

function Car(brand, model, year, color) {
    Vehicle.call(this, brand, model, year); // Call the Vehicle constructor
    this.color = color;
}

// Set Car's prototype to an instance of Vehicle
Car.prototype = Object.create(Vehicle.prototype);
Car.prototype.constructor = Car; // Reset constructor

Car.prototype.drive = function() {
    return `The ${this.color} ${this.brand} ${this.model} is driving!`;
};

let myCar = new Car('Toyota', 'Corolla', 2022, 'blue');

console.log(myCar.start()); // Output: Toyota Corolla started!
console.log(myCar.drive()); // Output: The blue Toyota Corolla is driving!
Enter fullscreen mode Exit fullscreen mode


Part 2 will cover some essential concepts of Object-Oriented Programming, such as Encapsulation, Abstraction, and Polymorphism. 🔥


Happy Coding! đź’Ş

Top comments (5)

Collapse
 
eduardopazz profile image
Info Comment hidden by post author - thread only accessible via permalink
Edu Paz

I think it's important to emphasize that Javascript is NOT "fundamentally" OOP.

All the class syntax brought in ES6 is just a syntactic sugar for what can be done with plain functions, closures, prototypes and stuff.

It's way different from Java's OOP, for instance.

I personally prefer to work with plain functions and modules instead of replicating classes in a language not made for such paradigm

Collapse
 
efpage profile image
Eckehard

Though I do not like the expression "syntactic sugar" we still have to state that the class concept of JS has some serial issues:

  • JS lacks any kind of access specifiers. Many oop-languages do not only know private or public properties, but also ways to define, how elements could be accessed in derived classes
  • JS objects are not fully encapsulated, so you lack a most important concept of OO. You will still need JS workarounds like IIFE´s to protect your code.
  • the use of "this" in classes is a pure mess. It was a compromise to make class objects compatible to conventional JS objects, but leads to horrible code. In most languages, class code is not much different from code in functions and procedures, but in JS it is. You cannot define a variable in a class using let or var, but have to use "this" without any specifier.
  • Additionally, the new class based syntax and the old prototype based syntax can be used side by side which might make the confusion complete.

So, today you can use OOP methods in JS, but you cannot expect the same benefits like you get in other languages.

Collapse
 
urielsouza29 profile image
Uriel dos Santos Souza

Oop not class!
here is no one “canonical” definition of OOP. There are at least two of them.

Two big schools of Object-Oriented Programming | stereobooster.github.io

TL;DR There is no one “canonical” definition of OOP. There are at least two of them. From my POV there are two big definitions, which deserves separate names. I named them after biggest advocates. Those two definition have some differences and some commonalities. I was about to get into another argue on OOP on the internet. I decided to do some research on the subject. I found more than one definition of OOP. Some of the definitions are variations of the same “tune”, some are useless. On my opinion there are two main directions of thoughts in this domain, which from two schools of OOP. School as in school of thought. The same way as there were philosophical schools in ancient Greece. The same way there are two schools of OOP: Alan Kay’s school or message focused Bjarne Stroustrup’s school or class focused or “PolymorphismEncapsulationInheritance” in terms of c2 I must emphasize that this article is not about what is best way to do OOP, because such discussion will lead to holy war. Instead purpose of this article is to help to recognize the fact that there are two ways to think about OOP. I believe this will help to build more constructive discussions about OOP. Next time you will start discussion on OOP or OOP vs make sure you know which school of OOP you are talking about. About names I choose Alan Kay and Bjarne Stroustrup as founders of schools, because they are big advocates of OOP and authors of first OOP languages of each school correspondingly. I’m aware that there are arguments on which programming language is the first OOP language and who invented OOP. See history section. Kay's school Stroustrup's school

stereobooster.github.io
Thread Thread
 
efpage profile image
Eckehard

If you look into history, you will find far more definitions, like "Objects exchanging messages". The class based approach in JS is clearly inspired by languages like C++, where OOP is more an extension to organize your procedural code.

Collapse
 
alisamirali profile image
Ali Samir

Object Oriented Programming With JavaScript - Part 2 🚀

dev.to/alisamirali/object-oriented...

Some comments have been hidden by the post's author - find out more