Lesson 7 of 1910:03 video

JavaScript classes and prototypes

How a class works as a blueprint and what new does when it builds an object from one, where methods really live (the prototype, and the chain JavaScript climbs to find them), why two different arrays share a single push, and how extends, super and instanceof follow from that chain.

In this lesson

  1. 0:00 Intro
  2. 1:07 One blueprint
  3. 3:26 Where methods live
  4. 5:42 Back to the arrays
  5. 6:44 Extending a class
  6. 9:22 Next time

Transcript

Intro

Here are two arrays: a crew, and a cargo list. Different arrays, with different things in them. Now compare their push methods: crew dot push, triple equals, cargo dot push. True. Not two functions that match. One function. Two arrays, one push. And it gets stranger. Ask whether the crew array has a push property of its own. False. There's no push in the array. But crew dot push works. It always has. So where has push been all along? Today, we find out.

By the end of this video, you'll understand three things. One: how a class works as a blueprint, and how the keyword new builds objects from it. Two: where methods really live, in a shared object called the prototype, and how JavaScript finds them there. Three: how one class builds on another with extends and super, and why a shuttle still counts as a rocket.

One blueprint

Last time, we put functions inside objects, as methods, and met the word this: whatever is left of the dot at the call. We had three rockets, and we wrote each one out by hand. When a second rocket needed the launch method, we attached it ourselves, with an assignment. That works for three rockets. It won't work for three hundred. And every rocket has the same shape: a name, a fuel level, a launch method. We want to write that shape once and build every rocket from it. JavaScript's tool for that is the class. We'll write one, watch it build a fleet, and then look underneath it, because underneath is where push has been hiding.

A class starts with the keyword class, then a name, then curly braces. The name starts with a capital letter, by convention: Rocket. Inside the braces go methods, in the short form from last time, with no commas between them. One method name is reserved: constructor. It's the setup method. Ours takes a name and a fuel level, and stores each one on this. Under it goes launch, the same method as last episode. That's the whole class. A class isn't a rocket. It's the blueprint for one. To build a rocket, write the keyword new, the class name, and the values in parentheses: new Rocket, Kestrel, eighty. Twice more, for Heron and Osprey, and there's the fleet: three rockets from one blueprint, each with its own name and its own fuel, and all three can launch.

So what did new do? Slow it down. First, it makes a brand-new, empty object. Second, it runs the constructor, with this set to that empty object. So this dot name equals name writes the name onto the new rocket, and the next line writes the fuel. Last time, this came from what's left of the dot. With new, it's the object being built. Third, it hands the finished object back, and that's what the variable gets. The constructor never says return. new does that for it. Leave new out, and call Rocket like a plain function, and JavaScript stops you: TypeError, class constructor Rocket cannot be invoked without new.

Where methods live

Now look at what new built. Print Kestrel, and the console shows a name and a fuel level. No launch. Ask whether Kestrel has a launch property of its own: false. The same answer the array gave. But kestrel dot launch runs. And compare kestrel dot launch with heron dot launch: true. One function, shared. So where is it? When JavaScript read the class, it built one extra object and put launch inside it. That object is the prototype. You can reach it as Rocket dot prototype. And new has a step we skipped. Right after it makes the empty object, it links that object to the prototype. Every rocket carries that hidden link. So the constructor's values go on each rocket, and the methods go on the prototype, once. Three rockets, one prototype, one launch.

Here's how a rocket calls a method it doesn't hold. Write kestrel dot launch, and JavaScript looks in Kestrel first. Name, fuel, no launch. So it follows the link and looks in the prototype. Found. It runs the function, and this is what it always is: whatever is left of the dot. Kestrel. That's why this gets filled in at the call. One launch serves every rocket, so it can't know its rocket ahead of time. Every property read works that way: the object first, then its prototype, and the first match wins. Give Heron a launch of its own, and heron dot launch finds that one first, while the others keep sharing. And it's a link, not a copy. Add a refuel method to the prototype now, and rockets built before it existed can call it.

None of that arrived with classes. The keyword class dates from 2015. Prototypes go back to the nineties, and a class is a tidier way to set one up. The idea is bigger than JavaScript, too. A design pattern is a named solution to a problem that keeps coming up, and prototype is one of the classics: new objects take their behavior from an existing one. The classic version makes a copy. JavaScript keeps a link. We'll cover design patterns in a new series soon.

Back to the arrays

Which brings us back to the two arrays we started with. They're built the same way. Array is a class too, one that's built into JavaScript, and square brackets are a shortcut for building one. Every array carries a link to Array dot prototype, and that's where push lives, next to map, filter, sort and every other array method. The crew array holds its items and its length, nothing more. So crew dot push isn't found in the crew array. It's found one link up. The cargo list follows its own link to the same place, and that's why the two were equal. And the links keep going. Array dot prototype has a prototype too: Object dot prototype, which holds the few methods every object gets, like toString. Rocket dot prototype links there as well. Above that, the link is null, and the search stops. That's the prototype chain. Ask an object for a name, and JavaScript climbs the chain until it finds a match or runs out of links. If it runs out, the answer is undefined.

Extending a class

A chain gets longer when one class builds on another. Say the fleet needs a shuttle: a rocket that can also dock. You could copy the whole Rocket class and add to it, but then there are two launch methods to keep the same. So extend it instead: class Shuttle extends Rocket, with one method inside, dock. That one word, extends, links Shuttle dot prototype to Rocket dot prototype, and makes Rocket the parent class. Build one: new Shuttle, Condor, seventy. Shuttle has no constructor of its own, so Rocket's runs. Now call condor dot dock. JavaScript looks in Condor, then one link up, in Shuttle dot prototype, and finds it. Call condor dot launch. Not in Condor. Not in Shuttle dot prototype. One more link, to Rocket dot prototype, and there it is. Nothing was copied. A shuttle can do everything a rocket can, because the search keeps climbing.

Now give the shuttle something of its own to set up: seats. That takes a constructor, and a constructor in a class that extends another has one rule. Before it touches this, it has to call super. super stands for the parent class. Called like a function, it runs the parent's constructor: hand it the name and the fuel, and Rocket's constructor stores them, the way it does for every rocket. After that, this dot seats equals seats. Touch this first, and you get an error that says so: must call super constructor. super has a second use. Give Shuttle its own launch. The search finds it first, so for a shuttle it replaces Rocket's. But inside it, super dot launch calls the Rocket version. So a shuttle's launch does its own part, belts on, and then hands over to the launch every rocket shares.

One more question the chain can answer: what kind of object do I have? The operator is instance of. Ask whether Condor is an instance of Shuttle: true. An instance of Rocket: also true. Ask whether Kestrel is an instance of Shuttle: false. It doesn't ask which class built the object. It climbs the object's chain, looking for the class's prototype. Rocket dot prototype is on Condor's chain, so a shuttle counts as a rocket. Shuttle dot prototype isn't on Kestrel's.

Next time

That's classes and prototypes in one line: a class is a blueprint, new builds an object from it and links it to the prototype, methods live on the prototype and are found by climbing the chain, and extends adds one more link. Next time, we pick up the shortcuts modern JavaScript added: shorter ways to pull values out of objects and arrays, to copy them, and to build strings, where one line does the work of five.

Learn more