Lesson 2 · Unit 04
The JavaScript Underneath
this, closures, prototypes, equality, truthiness and promises
What you practise
thisand how it is lost, closures, classes over prototypes, equality and truthiness traps, promises andasynctyped
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?
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"); }Correct answer
threw
Why
Python binds self when you read c.inc. JavaScript does not: this is decided at the moment of the call, by what stands before the dot. f() has nothing there, so this is undefined and this.n throws. The compiler does not catch it.
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.
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 3Concept
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.
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); // true10 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.