Bitpath

Lesson 2 · Unit 07

This and inheritance

How this gets lost, and classes built on classes

13 exercisesabout 3 min

What you practise

  • How a method loses this and three ways to keep it, extends and super, the prototype chain in one picture, composing objects instead

Try a question from this lesson

Pick one

say holds the very same function as g.hello. But the last line calls it with no g. in front. What happens?

JavaScript
class Greeter {
  constructor(name) {
    this.name = name;
  }
  hello() {
    return "Hi " + this.name;
  }
}
const g = new Greeter("Ada");
const say = g.hello;
console.log(say());

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

this is decided by the call

In g.hello(), the object before the dot becomes this for that one call.

Take the method off its object, and the link is gone. This happens whenever you hand a method to other code to call later: a timer, map, a button.

The function is the same. Only the way it is called differs.

JavaScript
class Greeter {
  constructor(name) { this.name = name; }
  hello() { return "Hi " + this.name; }
}
const g = new Greeter("Ada");
console.log(g.hello()); // Hi Ada

const say = g.hello; // just the function
// say() would throw: no object, no this

Concept

Arrow functions keep this

Fix three. An arrow function has no this of its own. It uses the this of the place where it was written.

Write a method as an arrow function stored in a field, and it is created inside each instance, tied to it forever. It can be handed around freely.

JavaScript
class Counter {
  n = 0;
  add = () => {
    this.n += 1;
  };
}
const c = new Counter();
const add = c.add; // taken off the object
add();
add();
console.log(c.n);  // 2

Concept

The prototype chain

Methods are not copied into every instance. Each object has a hidden link to a prototype: an object holding the methods of its class.

When you ask for something an object does not have, JavaScript follows the link and looks there, then one level further up, until it runs out of links.

class and extends build this chain for you.

tom               { name, lives }
  |  not here? look up
Cat.prototype     { purr }
  |
Animal.prototype  { eat }
  |
Object.prototype  { toString, ... }

9 more exercises in the app

  • 3× type the answer
  • 3× multiple choice
  • 2× fill the blanks
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy