Bitpath

Lesson 2 · Unit 04

The JavaScript Underneath

this, closures, prototypes, equality, truthiness and promises

13 exercisesabout 3 min

What you practise

  • this and how it is lost, closures, classes over prototypes, equality and truthiness traps, promises and async typed

Try a question from this lesson

Pick one

In Python, f = c.inc is a bound method and f() returns 1. This compiles in TypeScript. What does it print?

TypeScript
class Counter {
  n = 0;
  inc() { this.n += 1; return this.n; }
}
const c = new Counter();
const f = c.inc;
try { console.log(f()); }
catch { console.log("threw"); }

The ideas

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

Concept

this

this is not fixed when a method is defined. It is set at each call, from what stands before the dot: c.inc() runs with this as c. Take the function off the object, or pass it as a callback, and the call has no dot, so this is lost.

Two fixes: bind, or an arrow function, which has no this of its own and uses the one from where it was written.

TypeScript
class Counter {
  n = 0;
  inc() { return ++this.n; }
}
const c = new Counter();
c.inc();                    // this is c

const f = c.inc.bind(c);    // this fixed
const g = () => c.inc();    // dot kept
console.log(f(), g());      // 2 3

Concept

Classes over prototypes

A JavaScript class is a thin layer over prototypes. Fields such as name are stored on each instance. Methods are stored once, on Dog.prototype, and every instance links to it; a lookup that misses on the object continues up that chain.

Python does much the same with the instance __dict__ and the class. The difference that bites: here a method taken off its object is just a function.

TypeScript
class Dog {
  name = "Rex";
  bark() { return this.name + "!"; }
}
const d = new Dog();
const p = Dog.prototype;

console.log(Object.keys(d));  // ["name"]
console.log(typeof Dog);      // function
console.log(d.bark === p.bark);  // true

10 more exercises in the app

  • 2× fill the blanks
  • 4× type the answer
  • 3× multiple choice
  • 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