JavaScript Advanced: Closures, Async and Modules
Classes, this and Prototypes
In this lesson you will
- Write classes with constructors, methods and inheritance
- Explain how the value of this is decided
- Describe the prototype chain at a high level
Introduction
When a program grows, you often need many objects of the same kind: many users, many products, many enemies in a game. A class is a blueprint for making them. This lesson also explains this, the most confusing word in JavaScript, and what happens underneath.
Classes
A class describes what its objects have (data) and what they can do (methods). new builds an object from it.
constructorruns when you usenew. It sets up the object.thisrefers to the object being worked on, hererexorfido.
Quick quiz
What does the constructor of a class do?
Inheritance
extends lets a class build on another. super calls the parent.
A Cat is an Animal that gets everything for free and changes only what is different.
How is this decided?
For regular functions, this is decided by how the function is called, not where it is written.
obj.method():thisisobj.- A plain call,
method():thisisundefinedin strict mode (and in classes). new Thing():thisis the new object.
Taking a method out of its object loses this. Two fixes:
bindmakes a copy of the function withthisfixed.- Arrow functions have no
thisof their own. They use thethisof the code around them. In thetimerexample, the arrow function insidestartuses thethisofstart, so it updatestimer.seconds. That makes arrows handy for callbacks inside methods, but a poor choice for object methods themselves.
Quick quiz
Which statement about arrow functions and this is true?
Under the hood: prototypes
JavaScript classes are built on prototypes. Every object has a hidden link to another object, its prototype. When you look for a property and it is not on the object, JavaScript follows the link, then the next, until it finds it or reaches the end. This is the prototype chain.
bark is not on rex itself. It lives on Dog.prototype, shared by every dog, and found through the chain. That is why a thousand dogs do not need a thousand copies of bark.
Try it yourself
Create a class BankAccount with a balance, and methods deposit(amount) and withdraw(amount). Make withdraw throw an error if there is not enough money.
Summary
- Classes are blueprints.
constructorsets up the object andthisis the object in use. extendsandsupergive inheritance.thisdepends on how a function is called. Usebindor arrow functions to keep it.- Under the hood, objects find shared methods through the prototype chain.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading