DEV Community

Cover image for Javascript OOP-1 (Classes and Objects) -
Mysterio
Mysterio

Posted on

Javascript OOP-1 (Classes and Objects) -

Hello Guys today i am going to discuss OOP(Object Oriented Programming) in javascript.It is one of the Important concept in any programming langauge and makes your code cleaner , reusable and safer.

Lets get started...

Classes -

  • In JavaScript, classes are the special type of functions. We can define the class just like function declarations and function expressions.

  • The JavaScript class contains various class members within a body including methods or constructor.

  • A class can be defined by using a class declaration. A class keyword is used to declare a class with any particular name. According to JavaScript naming conventions, the name of the class always starts with an uppercase letter.

Example -

class Order{
     let orderNo = 1;
     let orderName = "Burger";
    display(){
     return "Order no. - " + orderNo + " " + "Order Name - " + 
     orderName;
    }
}
let object1 = new Order();
console.log(object1.display());
Enter fullscreen mode Exit fullscreen mode

Output -

Order no. - 1 Order Name - Burger
Enter fullscreen mode Exit fullscreen mode

Explaination -

  • Here we have declared a class called "Order" and inside it we have created a method called "display()".
  • Then inside display we have created two variables called orderNo with value 1 and orderName with value "Burger" and return their value using return statment.
  • Then we created the object of Order class (we will discuss Objects after this topic) and then called the display() method using the object we have created using "." dot operator.

Objects -

  • A javaScript object is an entity having state and behavior (properties and method).
  • JavaScript is an object-based language. Everything is an object in JavaScript.
  • JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct create objects.

  • There are 3 ways to create objects-
    1 Object Literal -

let order = {orderNo : 1 , orderName : "Burger"};
Enter fullscreen mode Exit fullscreen mode

Output -

1 Burger
Enter fullscreen mode Exit fullscreen mode

2 By using new keyword -

let order =  new Object();
order.orderNo = 1;
order.orderName = "Burger";
Enter fullscreen mode Exit fullscreen mode

Output -

1 Burger
Enter fullscreen mode Exit fullscreen mode

3 By using an Object constructor -
Here, you need to create function with arguments. Each argument value can be assigned in the current object by using "this" keyword.

function order(orderNo , orderName){
this.orderNo = orderNo;
this.orderName = orderName;
}

newOrder = new order(1 , "Pizza");
Enter fullscreen mode Exit fullscreen mode

Output-

1 Pizza
Enter fullscreen mode Exit fullscreen mode

Object with Class -

We can create objects of classes as objects are the instance of class and class is the blueprint of objects.

Example -

class Superhero{
    powers(){
        let heroName = "Superman";
        let superPower = "Super strength , Flying and Heat Vision";

        return "Hero Name - " + heroName + 
" Super Powers - " + superPower; 
    }
}

let Character = new Superhero();
console.log(Character.powers());
Enter fullscreen mode Exit fullscreen mode

Output-

Hero Name - Superman 
Super Powers - Super strength , Flying and Heat Vision
Enter fullscreen mode Exit fullscreen mode
  • As you can see we have created a class named "Superhero" and then created its object using new keyword and stored it in a variable called "Character".

THANK YOU FOR READING THIS POST AND IF YOU FIND ANY MISTAKE OR WANTS TO GIVE ANY SUGGESTION , PLEASE MENTION IT IN THE COMMENT SECTION.

^^You can help me by some donation at the link below Thank you👇👇 ^^

☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well

  1. https://dev.to/shubhamtiwari909/animation-with-react-spring-3k22

  2. https://dev.to/shubhamtiwari909/text-to-speech-in-reactjs-52ml

  3. https://dev.to/shubhamtiwari909/best-vs-code-extensions-for-web-development-2lk3

  4. https://dev.to/shubhamtiwari909/introduction-to-tailwind-best-css-framework-1gdj

Discussion (9)

Collapse
lukeshiru profile image
Luke Shiru

Is a pretty common misconception to include inheritance and classes as part of OOP, but they aren't actually part of it.

The pioneer of OOP, Alan Kay, when talking about the meaning of OOP, said:

OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things.

So the actual basic ingredients of OOP are:

  • Message passing.
  • Encapsulation.
  • Dynamic binding.

You might notice that classes are not considered essential. Classes are just one way of doing encapsulation, but JavaScript (and by consequence TypeScript) have other ways of achieving encapsulation that are more flexible and composable than classes, namely functions, closures and modules.

Your first snippet is invalid JS, let can't be used to declare class properties, so the fixed version is:

class Order {
    #number = 1;
    #name = "Burger";

    display() {
        return `Order no. - ${this.#number} Order Name - ${this.#name}`;
    }
}
const order = new Order();
console.log(order.display()); // "Order no. - 1 Order Name - Burger"
Enter fullscreen mode Exit fullscreen mode

You can see that we can achieve the same thing with a closure:

const createOrder = () => {
    const order = {
        number: 1,
        name: "Burger"
    }

    return {
        display() => `Order no. - ${order.number} Order Name - ${order.name}`
    }
}

const order = createOrder();
console.log(order.display()); // "Order no. - 1 Order Name - Burger"
Enter fullscreen mode Exit fullscreen mode

Or better yet, we can just make it functional:

const displayOrder = ({ number, name }) =>
    `Order no. - ${number} Order Name - ${name}`;

console.log(
    displayOrder({
        number: 1,
        name: "Burger",
    }),
); // "Order no. - 1 Order Name - Burger"
Enter fullscreen mode Exit fullscreen mode

Same applies to the Superhero class. This one luckily doesn't have invalid syntax, but is being used in a really weird way, here's how that class implementation could look like:

class Superhero {
    #name = "Superman";
    #power = "Super strength , Flying and Heat Vision";

    powers() {
        return `Hero Name - ${this.#name} Super Powers - ${this.#power}`;
    }
}

const superhero = new Superhero();
console.log(superhero.powers());
// "Hero Name - Superman Super Powers - Super strength , Flying and Heat Vision"
Enter fullscreen mode Exit fullscreen mode

Following the same treatment Order got, we can use closure:

const createSuperhero = () => {
    const superhero = {
        name: "Superman"
        power: "Super strength , Flying and Heat Vision",
    }

    return {
        powers() => `Hero Name - ${superhero.name} Super Powers - ${superhero.power}`
    }
}

const superhero = createSuperhero();
console.log(superhero.powers());
// "Hero Name - Superman Super Powers - Super strength , Flying and Heat Vision"
Enter fullscreen mode Exit fullscreen mode

And the functional approach:

const superheroPowers = ({ name, power }) =>
    `Hero Name - ${name} Super Powers - ${power}`;

console.log(
    superheroPowers({
        name: "Superman"
        power: "Super strength , Flying and Heat Vision",
    }),
);
// "Hero Name - Superman Super Powers - Super strength , Flying and Heat Vision"
Enter fullscreen mode Exit fullscreen mode

Hope this helps with the disambiguation of class and OOP, and also helps write code in JS without the need for class.

Cheers!

Collapse
hanpari profile image
Pavel Morava

Suffice it to say nobody really knows what the famous OOP is and how is defined. But since it had been coined it seems that everybody has tried to use and explain it.

My personal guess is that in ten years, the OOP will have the same reputation as procedural programming.

Collapse
shubhamtiwari909 profile image
Mysterio Author

With the advancement in technology day by day , OOP will lose its reputation like procedural

Collapse
shubhamtiwari909 profile image
Mysterio Author

I always use functional approach and these corrections helped me learn some new things thank you for that.
I just thought classes and objects are common topics that's why i tried to explain them

Collapse
prakashpaarthipan profile image
Prakash_DevOps

Nice snippets and explanation

Collapse
enetojara profile image
Ernesto Jara Olveda • Edited on

So you Is saying that a class could include methods or constructor. So a class can AND cannot have constructor? Interesting.

heroName and powerName are adjectives, so they should be attributes of the class, not local variables of a methods.

Collapse
shubhamtiwari909 profile image
Mysterio Author

A class body can contain methods and constructors isn't right ?

Collapse
enetojara profile image
Ernesto Jara Olveda

The constructor() method is called automatically when a class is initiated, and it has to have the exact name "constructor", in fact, if you do not have a constructor method, JavaScript will add an invisible and empty constructor method.

Thread Thread
shubhamtiwari909 profile image
Mysterio Author

By saying include , i meant the same
An invisible constructor will get invoked automatically if we don't create one