O'Reilly logo

You Don't Know JS: this & Object Prototypes by Kyle Simpson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Prototypes

In Chapters 3 and 4, we mentioned the [[Prototype]] chain several times, but haven’t said what exactly it is. We will now examine prototypes in detail.

Note

All of the attempts to emulate class-copy behavior described previously in Chapter 4, labeled as variations of mixins, completely circumvent the [[Prototype]] chain mechanism we examine here in this chapter.

[[Prototype]]

Objects in JavaScript have an internal property, denoted in the specification as [[Prototype]], which is simply a reference to another object. Almost all objects are given a non-null value for this property, at the time of their creation.

Note: we will see shortly that it is possible for an object to have an empty [[Prototype]] linkage, though this is somewhat less common.

Consider:

var myObject = {
    a: 2
};

myObject.a; // 2

What is the [[Prototype]] reference used for? In Chapter 3, we examined the [[Get]] operation that is invoked when you reference a property on an object, such as myObject.a. For that default [[Get]] operation, the first step is to check if the object itself has a property a on it, and if so, it’s used.

Note

ES6 Proxies are outside of our discussion scope in this book (they will be covered in a later book in the series), but everything we discuss here about normal [[Get]] and [[Put]] behavior does not apply if a Proxy is involved.

But it’s what happens if a isn’t present on myObject that brings our attention now to the [[Prototype]] link of the object.

The default [[Get]] operation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required