Tip 39: Extend Existing Prototypes with Class

In this tip, you’ll learn how to use classes with existing prototypes.

Now that you know how to write classes in JavaScript, it’s time to see how the new class syntax relates to JavaScript prototypes. It’s important to understand that classes in JavaScript and prototypes aren’t different. Classes are just a clean way to write regular JavaScript. By understanding how classes in JavaScript differ from traditional object-oriented languages, you’ll be able to integrate new syntax with legacy code and prevent subtle bugs from surfacing.

Differences between JavaScript & other object-oriented languages

What are the differences between JavaScript and more traditional object-oriented languages? Here are the basics: When you use a class in traditional object-oriented languages, such as Ruby, it’s a blueprint for an object. When you create a new instance, you copy all the properties and methods onto the new object.

JavaScript is a prototype language. When you create a new instance, you aren’t copying methods. You’re creating a link to a prototype. When you call a method on an instance of an object, you’re calling it from the prototype, which is itself an object instance (not a blueprint). Eric Elliot has a longer article on the subject.

When you see the word class in JavaScript, you should know that it isn’t new functionality. It’s just a shorthand for a prototype. That means you can integrate class syntax with your current code bases.

Constructor functions

Up to this point, you’ve created object instances from classes, but not from constructor functions. In pre-ES5 JavaScript, when you wanted to create a new object instance using the new keyword, you’d use a function. You’ll notice that constructor functions are very similar to a constructor method on a class. That should be a clue that new syntax will fit in nicely with legacy code.

To make an object instance with a constructor function in JavaScript, you’d simply write a function as normal. By convention, when you intend to use a function as a constructor, you’d start the function with a capital letter. Inside the function, you can attach properties to an instance using the this keyword.

When you create a new instance using the new keyword, you run the function as a constructor and bind the this context.

Example

Here’s Coupon written as a constructor function.

Get hands-on with 1200+ tech skills courses.