How Well Do You Know this?

JavaScript's this keyword is one of the most misunderstood features in the language. Unlike other languages where this refers to the enclosing class instance, in JavaScript this is a runtime binding determined entirely by how and where a function is called: its call site.

There are four binding rules, applied in order of precedence. Understanding them lets you predict exactly what this will refer to in any context, without guessing or reaching for .bind() by reflex.

The four binding rules

1. new binding: When a function is called with new, a brand new object is created and this inside the function refers to that object.

2. Explicit binding: Using .call(), .apply(), or .bind() explicitly sets this to the provided object, regardless of call site.

3. Implicit binding: When a function is called as a method of an object (obj.fn()), this refers to that object. The binding can be lost if the function is extracted and called independently.

4. Default binding: The fallback when none of the above apply. In strict mode, this is undefined; in non-strict mode, it falls back to the global object.

The full article on Medium walks through each rule with annotated code examples, explains binding loss, and covers arrow functions, which don't have their own this at all.

// Read the full article

Read on Medium ↗
Also on: Dev.to HackerNoon

// Also by Animesh

Fundamentals of Functional JavaScript 21 min read

Animesh Pandey — Resume