Olson CloudWorks 🚀

When do you use the this keyword closed

September 19, 2026

📂 Categories: C#
When do you use the this keyword closed

The “this” keyword in JavaScript can be a source of confusion for many developers, especially those new to the language or coming from other programming paradigms. Understanding when do you use the “this” keyword is crucial for writing effective and maintainable JavaScript code. It’s not simply a reference to the current object; its value changes depending on the context in which it’s used. This context, often referred to as the execution context, determines what “this” refers to at any given point in your code. We’ll demystify this concept by exploring various scenarios and providing practical examples, ensuring you grasp the nuances of “this” and can confidently apply it in your projects. Mastering “this” is essential for working with objects, methods, and event handlers in JavaScript, leading to more robust and predictable applications.

“This” in Global Context

In the global execution context (outside of any function), “this” refers to the global object. In web browsers, this is typically the window object. In Node.js, it’s the global object. This means that any variables declared outside of a function using var will be added as properties to the global object. For instance, if you execute var myVar = 10; outside of any function in a browser, you can access it via window.myVar. This behavior differs slightly when using let or const, as these create variables in the global scope but do not attach them to the global object.

However, relying on the global context for “this” can lead to unexpected behavior and is generally discouraged in modern JavaScript development. It’s best practice to use modules or other scoping mechanisms to avoid polluting the global namespace. According to Mozilla Developer Network (MDN), “In most cases, the value of this is determined by how a function is called” [1]. This highlights the importance of understanding how function calls affect the value of “this”.

Consider this example:

var myVar = 20; console.log(this.myVar); // Output: 20 (in browsers if not using strict mode) 

“This” Inside Functions

The value of “this” inside a function is more dynamic and depends on how the function is called. There are several ways a function can be invoked, each affecting the value of “this” differently. These include direct function calls, method invocations, constructor calls, and indirect invocations using call, apply, and bind. Understanding these different invocation patterns is key to mastering the “this” keyword.

When a function is called directly (e.g., myFunction()), “this” typically refers to the global object (window in browsers, global in Node.js) or is undefined in strict mode. However, when a function is called as a method of an object (e.g., myObject.myMethod()), “this” refers to the object that the method is being called on (myObject in this case). This is one of the most common and important uses of “this” in object-oriented JavaScript.

For example:

const myObject = { myVar: 30, myMethod: function() { console.log(this.myVar); } }; myObject.myMethod(); // Output: 30 

In this featured snippet-optimized paragraph, we highlight the most crucial aspect: When do you use the “this” keyword inside a function? The answer is: you use it to refer to the object that the function is a method of, allowing the function to access and manipulate the object’s properties. This is fundamental to object-oriented programming in JavaScript and allows for creating reusable and modular code.

“This” in Constructor Functions

Constructor functions are used to create objects in JavaScript. When a function is invoked using the new keyword, it acts as a constructor. Inside a constructor function, “this” refers to the newly created object. This allows you to initialize the object’s properties and methods. This pattern is essential for creating reusable object blueprints.

The new keyword performs several important actions: it creates a new empty object, sets the prototype of the new object to the constructor function’s prototype property, binds “this” to the new object, and implicitly returns the new object (unless the constructor explicitly returns a different object). If the constructor does not return a value, the new expression will return the newly created object.

Consider the following example:

function Person(name) { this.name = name; this.sayHello = function() { console.log("Hello, my name is " + this.name); } } const person1 = new Person("Alice"); person1.sayHello(); // Output: Hello, my name is Alice 

“This” with Call, Apply, and Bind

JavaScript provides methods call, apply, and bind that allow you to explicitly set the value of “this” when calling a function. These methods are particularly useful when you need to call a function in a specific context or when working with event handlers.

The call and apply methods invoke a function with a given “this” value and arguments. The main difference between them is how arguments are passed: call accepts arguments individually, while apply accepts them as an array. The bind method, on the other hand, creates a new function with the specified “this” value, which can be invoked later. According to the documentation, “The bind() method creates a new function that, when called, has its this keyword set to the provided value” [2].

Here’s an example demonstrating the use of call:

const person = { name: "Bob", greet: function(greeting) { console.log(greeting + ", my name is " + this.name); } }; const anotherPerson = { name: "Charlie" }; person.greet.call(anotherPerson, "Hi"); // Output: Hi, my name is Charlie 
  • call and apply invoke the function immediately.
  • bind returns a new function that can be invoked later.

Arrow Functions and “This”

Arrow functions introduce a different behavior for “this”. Unlike regular functions, arrow functions do not have their own “this” context. Instead, they inherit the “this” value from the surrounding (enclosing) scope. This is known as lexical scoping. This behavior can simplify code and avoid common pitfalls associated with “this” in callbacks and event handlers.

Because arrow functions don’t bind their own “this”, they are often used in situations where you want to preserve the “this” value from the surrounding context. This is especially helpful in methods of objects where you need to access the object’s properties within a callback function. Using a regular function in such cases would require using bind or storing “this” in a variable (e.g., var self = this;), which can make the code more verbose and less readable.

For instance:

const myObject = { myVar: 40, myMethod: function() { setTimeout(() => { console.log(this.myVar); // Output: 40 }, 1000); } }; myObject.myMethod(); 
Infographic here
Best Practices for Using "This" -------------------------------

To avoid confusion and write more maintainable code, it’s important to follow some best practices when using “this”. Always be mindful of the execution context and how it affects the value of “this”. Use arrow functions when you want to inherit the “this” value from the surrounding scope. Avoid relying on the global context for “this”, and use modules or other scoping mechanisms instead. When working with event handlers, be aware of how “this” is bound by the event listener.

Using strict mode ("use strict";) can help catch errors related to “this”. In strict mode, “this” is undefined when a function is called directly, which can prevent accidental modification of the global object. According to W3Schools, “When used in a function, this refers to the owner of the function” [3]. Understanding this rule helps to determine the value of this in different scenarios.

Here are some key takeaways:

  • Understand the different ways a function can be invoked and how each affects the value of “this”.
  • Use arrow functions when you want to inherit the “this” value from the surrounding scope.
  1. Identify the execution context of the function.
  2. Determine how the function is being called (direct, method, constructor, etc.).
  3. Apply the appropriate rules to determine the value of “this”.

Read more about JavaScript fundamentals.FAQ About the “This” Keyword

What is the "this" keyword in JavaScript?
The "this" keyword refers to the object that is currently executing the code. Its value depends on how the function is called.
How does "this" work in arrow functions?
Arrow functions do not have their own "this" context. They inherit the "this" value from the surrounding scope (lexical scoping).
What is the difference between `call`, `apply`, and `bind`?
`call` and `apply` invoke a function with a specified "this" value, while `bind` creates a new function with the specified "this" value.
What happens to "this" in strict mode?
In strict mode, "this" is `undefined` when a function is called directly.
With a clearer grasp of when and how to use "this", you're better equipped to write robust and predictable JavaScript. Experiment with the examples provided, practice in different scenarios, and continuously refine your understanding. The more you work with "this", the more intuitive it will become. Consider exploring related topics such as JavaScript closures and prototypes to further enhance your JavaScript skills. **Question & Answer :**
I was curious about how other people use the **this** keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples:

In a constructor:

public Light(Vector v) { this.dir = new Vector(v); } 

Elsewhere

public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); } 

I don’t mean this to sound snarky, but it doesn’t matter.

Seriously.

Look at the things that are important: your project, your code, your job, your personal life. None of them are going to have their success rest on whether or not you use the “this” keyword to qualify access to fields. The this keyword will not help you ship on time. It’s not going to reduce bugs, it’s not going to have any appreciable effect on code quality or maintainability. It’s not going to get you a raise, or allow you to spend less time at the office.

It’s really just a style issue. If you like “this”, then use it. If you don’t, then don’t. If you need it to get correct semantics then use it. The truth is, every programmer has his own unique programing style. That style reflects that particular programmer’s notions of what the “most aesthetically pleasing code” should look like. By definition, any other programmer who reads your code is going to have a different programing style. That means there is always going to be something you did that the other guy doesn’t like, or would have done differently. At some point some guy is going to read your code and grumble about something.

I wouldn’t fret over it. I would just make sure the code is as aesthetically pleasing as possible according to your own tastes. If you ask 10 programmers how to format code, you are going to get about 15 different opinions. A better thing to focus on is how the code is factored. Are things abstracted right? Did I pick meaningful names for things? Is there a lot of code duplication? Are there ways I can simplify stuff? Getting those things right, I think, will have the greatest positive impact on your project, your code, your job, and your life. Coincidentally, it will probably also cause the other guy to grumble the least. If your code works, is easy to read, and is well factored, the other guy isn’t going to be scrutinizing how you initialize fields. He’s just going to use your code, marvel at it’s greatness, and then move on to something else.