Member-only story

Quick Reference for the “this” keyword in JavaScript

Marika Lam
Nov 5, 2020

--

this refers to an object which is executing the current bit of JavaScript code. There are 4 rules.

1. Simple Function Call

this is the global object in non-strict mode, and undefined in strict mode.

2. Implicit Binding

this points to the object on which the function is called (what’s to the left of the period when the function is called)

3. Explicit Binding

We can explicitly tell the JavaScript engine to set this to point to a certain value using call, apply or bind.

4. new Binding

Using the new keyword constructs a new object, and this points to it.

Summary

The JavaScript this keyword refers to the object it belongs to

  • In a method — this refers to the owner object
  • Alone — this refers to the global object
  • In a function — this refers to the global object
  • In a function, in strict mode — this is undefined
  • In an event — this refers to the element that received the event
  • Methods like call() and apply() can refer to this to any object

--

--

No responses yet