The "this" Keyword

The this keyword in JavaScript is a special identifier that refers to the execution context of a function. Its value depends on how and where the function is called, not where it is defined.

Illustration of the_this_keyword
Illustration of the_this_keyword

💡 Key Concept

this is determined at runtime based on the invocation context, not lexical scope.

Common this Contexts

How this is set
ContextValue of this
Global function callwindow (browser) or global (Node.js) or undefined in strict mode
Method call (object property)The object owning the method
Constructor function (called with new)The newly created object
Arrow functionLexically inherited from enclosing scope
Explicit binding (call, apply, bind)Set explicitly to the first argument of these methods

1. Global Context

When a function is called in the global scope, this refers to the global object (unless in strict mode).

📌 Deep Dive: Global this

JAVASCRIPT
function show() {
  console.log(this);
}
show();
Output
Window {...} (browser) or global object

2. Object Method

When called as a method, this refers to the object before the dot.

📌 Deep Dive: Method this

JAVASCRIPT
const user = {
  name: 'Alice',
  greet() {
    console.log(this.name);
  }
};
user.greet();
Output
Alice

3. Constructor Functions

When a function is called with new, this points to the newly created object.

📌 Deep Dive: Constructor this

JAVASCRIPT
function Person(name) {
  this.name = name;
}
const p = new Person('Bob');
console.log(p.name);
Output
Bob

4. Arrow Functions

Arrow functions do NOT have their own this. Instead, they inherit this from the surrounding lexical scope.

📌 Deep Dive: Arrow Function this

JAVASCRIPT
const obj = {
  name: 'Carol',
  regular() {
    console.log(this.name);
  },
  arrow: () => {
    console.log(this.name);
  }
};
obj.regular(); // Carol
obj.arrow();   // undefined (or global this.name)
Output
Carol
undefined

⚠️ Arrow Function Gotcha

Do not use arrow functions as object methods if you need to access the object via this because they don't have their own this.

5. Explicit Binding

You can explicitly set the value of this using call, apply, or permanently bind with bind.

📌 Deep Dive: Explicit this Binding

JAVASCRIPT
function showName() {
  console.log(this.name);
}
const user = { name: 'Dave' };
showName.call(user);  // Dave
const bound = showName.bind(user);
bound();              // Dave
Output
Dave
Dave

💡 Summary

  • this depends on call-site, not function definition.
  • Arrow functions inherit this lexically.
  • Use call, apply, or bind to change this explicitly.
  • Be cautious with this inside event handlers or callbacks.