Chapter 6. Object-orientation with prototypes

 

In this chapter we discuss

  • Using functions as constructors
  • Exploring prototypes
  • Extending objects with prototypes
  • Avoiding common gotchas
  • Building classes with inheritance

Now that we’ve learned how functions are first-class objects in JavaScript, and how closures make them incredibly versatile and useful, we’re ready to tackle another important aspect of functions: function prototypes.

Those already somewhat familiar with JavaScript prototypes might think of them as being closely related to objects, but once again it’s all about functions. Prototypes are a convenient way to define types of objects, but they’re actually a feature of functions.

Prototypes are used throughout JavaScript as a convenient means of defining properties and functionality that will be automatically applied to instances of objects. Once defined, the prototype’s properties become properties of instantiated objects, serving as a blueprint of sorts for the creation of complex objects.

In other words, they serve a similar purpose to that of classes in classical object-oriented languages. Indeed, the predominant use of prototypes in JavaScript is in producing a classical style of object-oriented code and inheritance.

Let’s start exploring how.

6.1. Instantiation and prototypes

6.2. The gotchas!

6.3. Writing class-like code

6.4. Summary

sitemap