“THIS” in JS

Keesha Hargrove
2 min readJun 6, 2022

The term “context” is used in JavaScript to refer to an object. The keyword “this” refers to that object (i.e. “self”), and provides an interface to the properties and methods that are members of the object. When a function is executed, the keyword “this” refers to the object in which the function is executed.

The following are a few scenarios:

  • “This” refers to the global, or “window” object, when a function is called in the global context
  • In the case of a method of an Object, “this” refers to that Object (unless the method is manually executed within a different object).
  • “This” can refer to either the object within which a function executes (no matter how deeply nested) or the object whose context it executes within
  • Within an instance object, you reference the instance object as “this”, when instantiating a constructor function

Geeksforgeeks explains it best : “ https://www.geeksforgeeks.org/this-in-javascript/ “ :

“The this keyword in JavaScript has often been a source of much confusion for beginners to the language. Some of this confusion stems from the fact that this in JavaScript is treated differently as compared to in other languages like in Java or self in Python.

Understanding this is absolutely imperative in order to understand more advanced concepts in JavaScript or to read and write JavaScript code, which is why we shall spend this article trying to clarify what this really means in JavaScript.
We shall spend much of the article learning about this with reference to functions in JavaScript, which is why we shall first look at a fact about JavaScript functions that will help us do this better.

this and Functions

Functions, in JavaScript, are essentially objects. Like objects they can be assigned to variables, passed to other functions and returned from functions. And much like objects, they have their own properties. One of these properties is this.
The value that this stores is the current execution context of the JavaScript program.Thus, when used inside a function this‘s value will change depending on how that function is defined, how it is invoked and the default execution context.”

--

--