javascript · level 3 · unit 2 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Methods live on a that every instance shares.
Classes are a friendlier way to write something older: prototypes. Methods are not copied into each instance. They live once on the class's prototype object, and every instance links to it. A thousand orders share one total method.
When you read rex.speak, JavaScript looks on rex first. Missing? It follows the link to the prototype, then to that prototype's prototype. This is the . walks the same chain to ask: was this object built by that class, or by a child of it?
class Animal { speak() { return "Hello"; } }
class Dog extends Animal { fetchBall() { return "Got it!"; } }
const rex = new Dog();
console.log(Object.getPrototypeOf(rex) === Dog.prototype);
console.log(rex.speak === new Animal().speak);
console.log(Object.hasOwn(rex, "speak"));
console.log(rex instanceof Dog, rex instanceof Animal, rex instanceof Array); Object.getPrototypeOf(x) shows the object x falls back on, and Object.hasOwn(x, key) asks whether x holds key itself.
guess first
A method added late. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Cat {
constructor(name) { this.name = name; }
}
const tom = new Cat("Tom");
Cat.prototype.purr = function () { return `${this.name} purrs`; };
console.log(tom.purr());
tom.purr = () => "Tom hisses";
console.log(tom.purr(), new Cat("Kit").purr());
your turn
Your turn. Let instanceof pick the words.
Fill in the class the first check should look for, then choose a radius for the circle.
fix it
The light forgot its room. Can you fix it?
- The trouble is
thison line 4. What kind of function isdescribe? - Arrow functions have no
thisof their own, sothis.roomdoes not mean the light. - Swap the arrow function for an ordinary
function () { }whose body returns the same template literal.
nailed it
you looked under the bonnet of classes. :D
- Methods live once on a prototype that instances share.
- Missing properties are searched for along the prototype chain.
instanceofasks whether a class is on that chain.
new words in your collection
- prototype
- prototype chain
- instanceof
This lesson isn’t saved. A free account remembers every lesson you finish.