Chapter 8 of 34
~11 min`this`, Prototypes & Classes
The value of `this` and how objects inherit behavior from one another are two of the trickiest but most interview-relevant JavaScript topics. Classes make this easier to work with, but underneath they are still built on the same prototype chain.
How `this` Is Determined
Unlike many languages, `this` in JavaScript is not fixed by where a function is defined - it is determined by how the function is called (the "call-site"). Call a method as `obj.method()` and `this` is `obj`. Call the same function standalone, detached from its object, and `this` becomes `undefined` (in strict mode) or the global object.
Arrow functions are the exception: they do not bind their own `this` at all, and instead capture whatever `this` was in the surrounding scope when they were defined.
Try it yourself
this depends on the call-site<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
call, apply, and bind
These three methods let you control `this` explicitly. `fn.call(obj, a, b)` calls `fn` with `this` set to `obj` and arguments passed individually. `fn.apply(obj, [a, b])` does the same but takes arguments as an array. `fn.bind(obj)` does not call the function - it returns a new function permanently bound to `obj`, useful for passing a method as a callback without losing its `this`.
Try it yourself
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Prototypes and Prototypal Inheritance
Every JavaScript object has an internal link to another object called its prototype. When you access a property that does not exist directly on an object, JavaScript walks up this "prototype chain" looking for it. This is how methods like `.map()` are shared across every array instance without being copied onto each one.
ES6 Classes
The `class` keyword is syntactic sugar over the same prototype system - a `class` still creates functions and prototype links under the hood, it just reads more like classes in other languages. `constructor` sets up instance properties, `extends` creates a subclass, and `super()` calls the parent class's constructor.
Try it yourself
A class with inheritance<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Coding challenge
Create a Vehicle class with a constructor that takes make and sets this.make, plus a describe() method returning "This is a <make> vehicle." Create a Car class that extends Vehicle. Instantiate a Car with make "Toyota" and log the result of calling describe().
<div id="output" style="font-family: sans-serif; padding: 12px; line-height: 1.6;"></div>
Answer every question below to mark this chapter as complete.
Quiz Yourself
Score: 0/41. What determines the value of `this` inside a regular function?
2. What does `fn.bind(obj)` return?
3. What is the prototype chain used for?
4. What is an ES6 `class` under the hood?