Lesson 3 of 12 · 10 min · Core language
this, prototypes and classes
What you will learn
- The rules that decide what
thisis call,apply,bindand how arrow functions differ- The prototype chain and
Object.create - ES6 classes: constructors, methods,
extends,super, static and private members - The classic
thisbugs and how to avoid them
In simple words
In many languages, this always means "the object this method belongs to". In JavaScript, this is decided by how a function is called, not where it is written, which is why it surprises everyone. Separately, JavaScript objects can inherit from other objects through a hidden link called the prototype, which is how methods are shared. Classes are a tidier way to write that same machinery.
Words to know
- this: a special value inside a function that depends on how the function was called.
- Prototype: the object that another object falls back on when a property is not found.
- Constructor: a function or class method that creates and initialises an object.
- Method: a function stored as a property of an object.
How `this` is decided
There are a few rules, from most to least specific:
new:new Person()creates a new object andthisis that object.- Explicit binding:
fn.call(obj),fn.apply(obj),fn.bind(obj)setthistoobj. - Method call:
obj.method()setsthisto the object before the dot. - Plain function call:
fn()givesthisasundefinedin strict mode (modules, classes) or the global object in sloppy mode. - Arrow functions have no
thisof their own: they use thethisof the surrounding code (lexicalthis).
const course = {
title: "SQL",
show() { return this.title; },
};
course.show(); // "SQL" (called as a method: this = course)
const detached = course.show;
detached(); // undefined in strict mode (TypeError if it reads a property on undefined)
setTimeout(course.show, 0); // the same loss: the function is passed alone, without its object
The method lost its object because passing course.show passes just the function. Fixes:
setTimeout(() => course.show(), 0); // call it as a method inside an arrow
setTimeout(course.show.bind(course), 0); // bind sets this permanently
call, apply and bind
function intro(greeting, punctuation) {
return `${greeting}, I am ${this.name}${punctuation}`;
}
const asha = { name: "Asha" };
intro.call(asha, "Hello", "!"); // arguments one by one
intro.apply(asha, ["Hello", "!"]); // arguments as an array
const hello = intro.bind(asha, "Hello"); // a NEW function with this (and a first argument) fixed
hello("?"); // "Hello, I am Asha?"
call and apply run immediately; bind returns a new function to call later. (apply is rarely needed since spread: fn.call(obj, ...args).)
Arrow functions and `this`
Arrow functions are best for callbacks because they keep the surrounding this:
class Timer {
seconds = 0;
start() {
setInterval(() => { this.seconds += 1; }, 1000); // `this` is the Timer: arrow keeps it
}
}
With a normal function () {} there, this would be wrong. But arrows are not suitable as object methods that need their own this, or as constructors:
const bad = { n: 1, inc: () => this.n++ }; // `this` is NOT bad: the outer this
Arrows also lack arguments and cannot be used with new. In React and modern code, arrow functions and closures mean you rarely write this at all.
Event handlers
In a DOM event listener written as a normal function, this is the element that received the event (event.currentTarget):
button.addEventListener("click", function () { console.log(this === button); }); // true
button.addEventListener("click", () => console.log(this)); // outer this, not the button
Prefer event.currentTarget and arrow functions so that you do not depend on this at all.
Prototypes
Every object has a hidden link to another object, its prototype. When you read a property that the object does not have, JavaScript looks at the prototype, then the prototype's prototype, and so on until null: the prototype chain.
const animal = { eats: true, walk() { return "walking"; } };
const dog = Object.create(animal); // dog's prototype is animal
dog.barks = true;
dog.barks; // true (own property)
dog.eats; // true (found on the prototype)
dog.walk(); // "walking"
Object.getPrototypeOf(dog) === animal; // true
"eats" in dog; // true (includes the chain)
Object.hasOwn(dog, "eats"); // false (own properties only)
Writing a property always creates it on the object itself (it does not change the prototype). Arrays inherit from Array.prototype (map, filter), functions from Function.prototype (call, bind), and nearly everything ends at Object.prototype (toString, hasOwnProperty).
Constructor functions were the old way to create objects that share methods:
function Person(name) { this.name = name; }
Person.prototype.greet = function () { return `Hi, ${this.name}`; };
const p = new Person("Asha");
p.greet(); // methods live once on Person.prototype and are shared
Object.getPrototypeOf(p) === Person.prototype; // true
Classes
ES6 classes are cleaner syntax over the same prototype system:
class Person {
static count = 0; // belongs to the class
#password; // private field (truly private)
role = "student"; // public field, set for each instance
constructor(name, password) {
this.name = name;
this.#password = password;
Person.count++;
}
greet() { return `Hi, I am ${this.name}`; } // on Person.prototype, shared
checkPassword(attempt) { return attempt === this.#password; }
get label() { return `${this.name} (${this.role})`; } // getter: used like a property
static create(name) { return new Person(name, "temp"); }
}
class Mentor extends Person {
constructor(name, password, skill) {
super(name, password); // must call super before using this
this.skill = skill;
}
greet() { return `${super.greet()} and I teach ${this.skill}`; }
}
const m = new Mentor("Ravi", "pw", "SQL");
m.greet(); // "Hi, I am Ravi and I teach SQL"
m instanceof Person; // true
Points to remember:
classis not hoisted like a function: it has a temporal dead zone.- A class body is always in strict mode.
- Methods are non-enumerable and live on the prototype; a class constructor cannot be called without
new. - Private members use
#and are enforced by the language (person.#passwordoutside the class is a syntax error);staticblocks andstaticmethods exist;getandsetdefine accessors. - A method passed as a callback loses
this, just like before: use an arrow-function field (handle = () => {...}) orbind. - Prefer composition and plain functions to deep class hierarchies; many JavaScript codebases use few classes (React function components use none).
Inspecting and debugging
console.log(Object.getPrototypeOf(obj)), obj instanceof Class, Object.keys(obj) (own enumerable keys), Object.entries(obj). In DevTools, expand an object and look at [[Prototype]] (or __proto__). Do not set __proto__ or use Object.setPrototypeOf in hot code (slow); use Object.create or classes.
Common mistakes
- Passing a method as a callback and losing
this. - Using an arrow function as an object method that needs
this. - Forgetting
super(...)beforethisin a subclass constructor. - Forgetting
newwith a constructor function (use classes to prevent it). - Putting mutable data on a prototype so that all instances share it.
- Deep inheritance trees instead of composition.
Try it yourself
- Create an object with a method that reads
this, detach it, call it, and fix it three ways (arrow,bind, wrapper). - Use
callandbindto borrow a method from another object. - Create
animalanddogwithObject.createand read inherited properties; list own versus inherited keys. - Write a
Personclass with a private field, a getter and a static factory, and aMentorsubclass usingsuper. - Make a
Timerclass whosesetIntervalcallback updatesthis.secondscorrectly.
Check yourself
What decides the value of this in a normal function?
How the function is called: with new, with call/apply/bind, as a method (obj.fn()), or as a plain call (undefined in strict mode).
How do arrow functions treat this?
They have no own this; they use the this of the enclosing scope where they were defined.
What is the prototype chain?
The sequence of objects JavaScript searches when a property is not found on an object: the object, its prototype, the prototype's prototype, up to null.
Are JavaScript classes a different inheritance system?
No. They are syntax over prototypes: methods live on the class's prototype and extends links prototypes.
Interview questions
Explain this in JavaScript.
It is determined at call time: the new object with new, the explicit object with call, apply or bind, the object before the dot in a method call, otherwise undefined in strict mode (or the global object in sloppy mode). Arrow functions capture this lexically.
What is the difference between call, apply and bind?
call invokes a function with a given this and arguments listed one by one; apply takes the arguments as an array; bind returns a new function with this (and optionally arguments) fixed.
What is prototypal inheritance?
Objects inherit directly from other objects through their prototype link; property lookups walk the chain, so methods can be shared without copying them.
Summary
thisdepends on the call:new,call/apply/bind, method call, plain call; arrow functions use the surroundingthis.- Lose-
thisbugs appear when methods are passed as callbacks: use arrows orbind. - Objects inherit through the prototype chain;
Object.createand classes build on it. - Classes give constructors,
extends/super, static and private members; prefer composition.
Going deeper
- MDN: this: the rules with examples.
- MDN: Inheritance and the prototype chain: the full guide.
- MDN: Classes: fields, private members and inheritance.
- MDN: Function.prototype.bind: reference.
See how much of this you can explain
A free mock interview asks you new questions on JavaScript from fundamentals to async for Frontend Developer and scores every answer, with what to fix.