JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript this Keyword


In JavaScript, the this keyword is one of the most fundamental and sometimes confusing concepts. It is a special reference that points to the object that is executing the current function, and its value depends on how and where a function is called.

Understanding this is essential for object-oriented programming, event-driven programming, and advanced function usage. Mastering this ensures that your code is predictable, reusable, and bug-free.

Global Context

In the global execution context, this points to the global object.

  • In browsers, the global object is window.

  • In Node.js, it is global.

console.log(this); // In browser: window

Variables declared with var become properties of the global object, whereas let and const do not.

var a = 10;
let b = 20;

console.log(this.a); // 10
console.log(this.b); // undefined
  • This distinction is important when accessing variables through this in different contexts.

Function Context

1. Regular Function Call

Inside a regular function, the value of this depends on strict mode.

function showThis() {
  console.log(this);
}

showThis(); // Non-strict mode: global object, Strict mode: undefined
  • In strict mode, this is undefined, which prevents accidental global references.

2. Method Call

When a function is called as a method of an object, this refers to the object that owns the method.

const person = {
  name: "Alice",
  greet: function() {
    console.log(this.name);
  }
};

person.greet(); // Alice
  • Here, this points to person.

3. Nested Functions

Nested functions do not inherit this from the outer function.

const person = {
  name: "Bob",
  greet: function() {
    function inner() {
      console.log(this);
    }
    inner();
  }
};

person.greet(); // Non-strict: window, Strict: undefined
  • To preserve this, use an arrow function or store this in a variable:

const person = {
  name: "Bob",
  greet: function() {
    const inner = () => console.log(this.name);
    inner();
  }
};

person.greet(); // Bob

Arrow Functions

Arrow functions do not have their own this. They inherit this from the lexical scope where they are defined.

const obj = {
  name: "Carol",
  arrowFunc: () => {
    console.log(this.name);
  }
};

obj.arrowFunc(); // undefined, because this comes from global scope
  • Use arrow functions inside methods to inherit the parent this:

const obj = {
  name: "Carol",
  greet: function() {
    const arrow = () => console.log(this.name);
    arrow();
  }
};

obj.greet(); // Carol
  • This is especially useful for callbacks and event handlers.

Classes and this

In ES6 classes, this refers to the instance of the class.

class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    console.log(this.name);
  }
}

const p1 = new Person("David");
p1.greet(); // David
  • Each instance has its own this.

  • this inside static methods refers to the class itself, not the instance.

Explicit Binding: call(), apply(), and bind()

JavaScript allows explicit control of this with call, apply, and bind.

function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}

const user = { name: "Eve" };

greet.call(user, "Hello");  // Hello, Eve
greet.apply(user, ["Hi"]);  // Hi, Eve

const boundGreet = greet.bind(user);
boundGreet("Hey");           // Hey, Eve
  • call and apply invoke the function immediately.

  • bind returns a new function with this permanently set.

this in Event Listeners

In DOM events, this refers to the element that triggered the event.

const button = document.querySelector("button");

button.addEventListener("click", function() {
  console.log(this); // The button element
});
  • Using an arrow function inherits this from the surrounding scope:

button.addEventListener("click", () => {
  console.log(this); // Window object (global)
});
  • Be careful when mixing regular and arrow functions in event handlers.

Best Practices

  1. Use arrow functions when you want to inherit this from the parent scope.

  2. Use bind() to ensure this has a fixed reference.

  3. Avoid using var for global variables, as it can confuse this.

  4. Prefer classes and methods for object-oriented code.

  5. Test this behavior in both strict and non-strict mode for clarity.

Summary of the Tutorial

  • this points to the execution context of a function or object.

  • In the global context, this is the global object.

  • In regular functions, this depends on how the function is called.

  • In object methods, this refers to the object.

  • Arrow functions inherit this from the surrounding scope.

  • Classes use this to refer to instances, and static methods refer to the class itself.

  • Explicit binding via call, apply, and bind allows precise control of this.

  • Correct understanding of this is essential for callbacks, event handlers, object-oriented code, and closures.

Mastering this ensures your JavaScript code is predictable, maintainable, and free of confusing runtime bugs.


Practice Questions

  1. Log this in the global context and explain the output in a browser and Node.js environment.

  2. Create a regular function and log this inside it. Compare the result in strict and non-strict mode.

  3. Define an object with a method and log this inside the method. Explain what this points to.

  4. Create a nested function inside a method and log this inside the nested function. Explain the behavior.

  5. Rewrite the nested function from the previous question using an arrow function and observe how this changes.

  6. Create a class with a method and log this inside the method. Instantiate the class and call the method.

  7. Create a static method in a class and log this inside it. Explain what this points to.

  8. Use call() and apply() to invoke a function with a specific this context. Compare the results.

  9. Use bind() to create a new function with this permanently set to a given object. Call the function and log the output.

  10. Create a DOM element and attach an event listener. Log this inside a regular function and then inside an arrow function. Explain the difference.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top