One of the most misunderstood features of JavaScript is its prototypal object system instead of the more familiar class-based one.
Most of the articles that you find on the Internet regarding JavaScript inheritance don't mention some important details, that I'm going to show you in this blog post series.
Let's start by saying that amongst the goals of JavaScript were to be easy to use by non-programmers and at the same time be familiar to experienced programmers.
Now, in order to be easy to use by non programmers, JavaScript has completely eliminated the notion of classes, but in order to be familiar enough to experienced programmers, it provided language constructs that would mimic the class behaviour, which ultimately led to confusion.
To further complicate the situation, there exist several libraries that mimic class-based systems in JavaScript, and even CoffeeScript, which aims to be only JavaScript with a nicer syntax, has introduced classes in its language.
Instead of fighting the language and trying to make it something that it's not, I prefer to understand how a classless prototypal object system works and embrace it.
Let's do a quick recap on how a class-based object system works by using the Python programming language as an example:
First of all you define a class like this:
class Rect:
def __init__(self, options):
# Initialize the object
def resize(self, options):
# Resize the rect
def move(self, options):
# Move the rect
Here the __init__ method is called the Constructor, and it is responsible for the object initialization. There also exists an object destructor (called __del__ in Python), that gets called automatically when the object is about to be garbage collected (or when the object gets explicitly deleted in non garbage-collected languages), but in this example it has not been used for simplicity.
In order to use this class, you have to instantiate it and make an object, like this:
my_rect = Rect({'left': 0, 'top': 0, 'width': 100, 'height': 100})
Notice that this one line actually does two things:
- It creates a class instance
- It calls the class constructor
Now that the object has been created, it can be used like this:
my_rect.move({'centerx': 200})
You can also make a derived class, that has all the base class properties, while adding some more specific ones:
class Sprite(Rect):
def __init__(self, options):
# Initialize the base class
Rect.__init__(self, options)
# Initialize the object
def setAnimation(self, options):
# Set the sprite animation
And of course, also the derived class must be instantiated:
my_sprite = Sprite({'left': 10, 'top': 10})
my_sprite.setAnimation({'animation': 'player'})
In the next blog posts I will show you how all these operations are performed using JavaScript and its prototypal object model, stay tuned.
Comments !