appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

this, prototypes and classes

Lesson 2 of 411 minAdvanced

What this points to, and what a class really is in JavaScript.

this depends on how a function is called

const user = {
  name: "Ana",
  hello() { return `Hi ${this.name}`; },
  later() { return () => this.name; },   // arrow function: keeps this from outside
};
user.hello();              // "Hi Ana"   (called as a method)
const f = user.hello;
f();                       // this is not user anymore: undefined name (or an error in strict mode)
const g = user.hello.bind(user);   // fixed to user
  • In a method call (obj.fn()), this is obj.
  • In a plain call, this is undefined in strict mode and modules.
  • Arrow functions have no this of their own: they use the one from where they are defined. Use them for callbacks inside methods.
  • call, apply and bind set this explicitly.

Prototypes

Objects inherit from other objects through a prototype chain. When you read obj.prop, JavaScript looks at obj, then its prototype, then that object's prototype, until it finds it or reaches null.

class Animal {
  constructor(name) { this.name = name; }
  speak() { return `${this.name} makes a sound`; }
}
class Dog extends Animal {
  speak() { return `${super.speak()}: woof`; }
}
console.log(new Dog("Rex").speak());
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype);   // true

class is syntax on top of prototypes. Methods live on Class.prototype, shared by all instances. Private fields start with # and are truly private: #balance.

CarefulNever merge untrusted objects into an existing object recursively without checks. Keys such as __proto__ can modify Object.prototype and affect your whole application (prototype pollution).

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What is this in an arrow function?
2. You do const f = user.hello; f(). Why can this lose its value?
3. What is a class in JavaScript?

Key terms