Objects, this and Prototypes

How this is bound, how prototypal inheritance works and what classes really are under the hood.

Intermediate · about 5 hours · difficulty 3/5

Learn first: Functions, Scope and Closures

JavaScript's object model is prototype-based. Classes exist, but they are syntax over prototypes, and this follows rules that trip up nearly everyone at first.

The four rules of this

The value of this depends on how a function is called, not where it is defined:

  1. Method call obj.fn(): this is obj.
  2. Plain call fn(): undefined in strict mode (modules are strict), the global object otherwise.
  3. Explicit binding with call, apply or bind.
  4. new: this is the newly created object.

Arrow functions have no this of their own; they capture it from the surrounding scope. That is why they are handy for callbacks inside methods, and why they make poor object methods. The classic bug: passing obj.method as a callback loses its this.

Prototypes

Every object has a hidden link ([[Prototype]]) to another object. Property lookups walk up this prototype chain until they find the key or hit null. Array methods like map live on Array.prototype, shared by every array.

Classes

class gives you constructors, methods, extends/super, static members, getters/setters and truly private #fields. Under the hood, methods are placed on the prototype. Modern frontend code uses classes less than it used to (React moved to functions), but you will meet them in libraries, Web Components and Angular.

Useful object tools

Destructuring, spread, Object.freeze, Object.entries, optional chaining (user?.address?.city), and getters for computed values.

Move on when you can explain why a method passed as an event handler loses this, and fix it three different ways.

Key concepts

  • Rules for this
  • Arrow functions and lexical this
  • call, apply and bind
  • Prototype chain
  • Classes, extends and super
  • Private fields and static members
  • Getters and setters
  • Object.create and Object.freeze

Mini project

Model a small shopping cart with a Cart class (private items field, add/remove/total methods, a getter for item count) and a DiscountCart subclass, then wire a button to cart.add and fix the lost-this bug.

Check yourself

Given const f = obj.greet; f(); what is this inside greet in a module, and why?

Free resources