Blog

Classes in JavaScript

Classes are among the murkier programming concepts in JavaScript, but they're as useful here as they are in other languages like Ruby. It's true that JS lacks a native class implementation, but there are easy ways to mimic the functionality of a solid class hierarchy system.

But first off, what the heck is a class? Put simply, classes describe the ingredients of your application. If you're writing a program for a library, you might have a book class, a customer class, and an event class.

In JavaScript, classes are constructor functions. They look like this:

To use your new class, assign a new instance of it to a variable:

When placed before a function call, the keyword "new" changes the context of that function to be the variable you're creating. So "this" in the Person function refers to our new variable, david. If we had called the function without the "new" keyword, "this" would refer to the global window, which is not only useless, but can causing naming collisions.

Now that we know how to use a class, how do we go about modifying one? There are two ways to approach this. We can change the class itself, or we change instances of that class. In our example, david is an instance of the class Person. Person is the actual class. To attach methods and properties to the class itself, you simply modify the variable Person:

This only affects the class, not instances of the class:

To modify instances of the class, like "david," we modify the parent class's prototype. You can think of a prototype as a blueprint for an object; it explains what methods an object can respond to. When we created an instance of the Person class, that object inherited Person's prototype. That means we can modify the prototype of Person and have those methods available on all the class's instances, including "david." That process looks like this:

That's it for today! In the next post we'll see how all this theory is used in the real world, specifically within Backbone.js.