OOP in Javascript

OOP in Javascript

OOP in Javascript

Recently I decided to make a new game with the game framework Phaser. Having only a tiny bit of experience in making games with Javascript I had to figure out a lot. Especially the OOP part of Javascript. Since Javascript does not (yet) use keywords like Class or Extends. In this post I will explain the basic OOP techniques like Declaring a class and extending classes like in Java. Please note that there are multiple ways of doing OOP in Javascript, this is just the way I found out working best for me.

Declaring a class

Declaring a class in Javascript is quite easy actually. Because almost everything in Javascript is an Object.

As you can see, I made a new variable and assigned it a function that takes 2 parameters.

In java it  is recommended to start the class names with a capital letter, thats why I start the variable with a capital letter.

The function does not only serve as the class, but also as the constructor. In this case we create a User class and give the constructor 2 variables, a name and an age.

Adding functions to the user class

A class is not really a class without having his own functions.

Here are 2 ways to give your class a function. You can just put it inside the class, like the printName function. or use prototype. Both ways allow you to use the this keyword. Personally I like to use the prototype way of declaring functions to your class.

Extending the user class

Extending a class in Javascript is a bit more tricky. Let me show you how it works with some code.

There, I create a new class called Developer and extended User. I can now create instances of Developer and call the functions from User.

Creating instances

Lets test the two classes I just made by creating some instances.

And the output of that code should be something like this.

Wrapping it up

Now you know how to do some basic OOP in Javascript. If you want to play around with this code or just see the whole source. It is available on jsfiddle: https://jsfiddle.net/fb603rc5/

Leave a Reply

Your email address will not be published. Required fields are marked *