Understanding OOP in JavaScript

Understanding OOP in JavaScript


Hey everyone! :wave: Today, I will explain what OOP is, what it is used for, and how to use it in JavaScript.

I hope you enjoy!


What is OOP?

OOP stands for Object-Oriented Programming. Wikipedia says:

Object-oriented programming (OOP) is a programming paradigm based on the concept of objects , which can contain data and code. The data is in the form of fields (often known as attributes or properties ), and the code is in the form of procedures (often known as methods ).

“Many of the most widely used programming languages (such as C++, Java, Python, etc.) are multi-paradigm and they support object-oriented programming to a greater or lesser degree, typically in combination with imperative, procedural programming.

Significant object-oriented languages include: Ada, ActionScript, C++, Common Lisp, C#, Dart, Eiffel, Fortran 2003, Haxe, Java, JavaScript, Kotlin, logo, MATLAB, Objective-C, Object Pascal, Perl, PHP, Python, R, Raku, Ruby, Scala, SIMSCRIPT, Simula, Smalltalk, Swift, Vala and Visual Basic.NET.”


What is OOP used for?

coursera states that:

“Object-oriented programming (OOP) is a way of thinking about and organizing code for maximum reusability. With this type of programming, a program comprises objects that can interact with the user, other objects, or other programs. This makes programs more efficient and easier to understand.”

Pros of OOP:

  • We can build the programs from standard working modules that communicate with one another, rather than having to start writing the code from scratch which leads to saving of development time and higher productivity,
  • OOP language allows to break the program into the bit-sized problems that can be solved easily (one object at a time).
  • The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost.
  • OOP systems can be easily upgraded from small to large systems.
  • It is possible that multiple instances of objects co-exist without any interference,
  • It is very easy to partition the work in a project based on objects.
  • It is possible to map the objects in problem domain to those in the program.
  • The principle of data hiding helps the programmer to build secure programs which cannot be invaded by the code in other parts of the program.
  • By using inheritance, we can eliminate redundant code and extend the use of existing classes.
  • Message passing techniques is used for communication between objects which makes the interface descriptions with external systems much simpler.
  • The data-centered design approach enables us to capture more details of model in an implementable form.

Cons of OOP:

  • The length of the programmes developed using OOP language is much larger than the procedural approach. Since the program becomes larger in size, it requires more time to be executed that leads to slower execution of the program.
  • We can not apply OOP everywhere as it is not a universal language. It is applied only when it is required. It is not suitable for all types of problems.
  • Programmers need to have brilliant designing skill and programming skill along with proper planning because using OOP is little bit tricky.
  • OOPs take time to get used to it. The thought process involved in object-oriented programming may not be natural for some people.
  • Everything is treated as object in OOP so before applying it we need to have excellent thinking in terms of objects.

Places that OOP is used within JavaScript would be things like:

  • Web and app development
  • GUI
  • Game development
  • Network Programming
  • Operating system
  • Testing and test automation

As you can see there are many benefits to using OOP with some disadvantages you would have to get used to.


How can we use OOP?

Now that we learned what OOP is and how we can use it, you probably want to learn how exactly we do this.
So in this tutorial we are using JavaScript to learn OOP.

In JavaScript to start using OOP we can create a class like this:

class ClassName {

}

Classes are places in which we can create objects. A class is basically a blueprint telling how we create these objects.

Note: In this tutorial I am going to create a class that makes a monster from some arguments.

So now we are going to create some arguments, but they aren’t done in the way you make functions.

class Monster {
    constructor(health, damage, type) {
        // ...
    }
}

To create arguments we need to use a constructor function, which initializes our new object. When we create this function one of the arguments always has this, as this allows you to pass variables around the class easily while having a variable only for that object.

class Monster {
    constructor(name, health, damage, level) {
        this.name = name;
        this.health = health;
        this.damage = damage;
        this.level = level;
    }
}

Now that we have our constructor function and we know what it’s for let’s create another important function that we can change in many ways to fit our purpose. The function we are going to use now is toString. The toString function says what we print out when we call our object. In my example I can do this something like this:

class Monster {
    // ...
    toString() {
    return ` 
${this.name}:

  HEALTH: ${this.health}
  DMG: ${this.damage}
  LEVEL: ${this.level}
`    }
}

Note: I use this as the argument so I can access the variables from the constructor function. We also use return instead of console.log to make sure our stuff gets printed correctly.

Now that we have our basic functions that are needed we can add functionality to our Class. In my example I am going to save my monster data to a JSON file.

class Monster {
    // ...
    saveData() {
        const data = {
            [this.name]: {
                HEALTH: this.health,
                DMG: this.damage,
                LEVEL: this.level
            }
        };

        fs.writeFileSync('monsterData.json', JSON.stringify(data));
    }
}

Note: In this example I did not show importing fs but still should be done if you are importing anything, like with normal programming import at the top of the file.

And then to call our function we can add them to our constructor.

class Monster {
    constructor(name, health, damage, level) {
        // ...
        this.saveData();
    }
}

Note: When calling a function in a Class make sure to put this. in front of it.

Now we are done with our Class code we can move on to making our object. If you want to do this in a separate file you can just make sure to import your Class file correctly.

We first want to initialize or curate our object, we can set it up with a variable like so:

const monster = new Monster("Gecko", 15, 10, 7);

Then we can print it out by using the console.log function and our object variable:

console.log(monster.toString());

Now we can change the health variable of the object and then save the monster data to a file.

monster.health -= 1; // reducing the health variable of the monster object by 1
monster.saveData(); // saving data

Note: To access the functions and variables of an object, you need to write the name of the object, then ., followed by the name of the variable or function.

And that’s it, we successfully learned OOP and created with OOP in JavaScript.
I hope you enjoyed and found this tutorial helpful!

Rate how good/helpful the tutorial was (1 Being Terrible - 10 Being Really Good/Helpful)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
0 voters

Created with :heart: by @SalladShooter

4 Likes

Isn’t this a JavaScript guide?

One of the codeblocks is broken

1 Like

I fixed it, check the edit

1 Like

Hmmm, its going back to the original form

@MiloCat what I did is copy over my python one (since it is pretty similar, I just changed the actual code things that would be different) and I guess I missed some stuff :rofl:.

I think I fixed it, it isn’t going back anymore.