Back to Web Development
2026-01-115 min read

Function this (Web Development)

Learn Function this (Web Development) step by step with clear examples and exercises.

Title: Mastering JavaScript's 'this' Keyword in Functions (Web Development)

Why This Matters

The 'this' keyword in JavaScript is a powerful tool that helps you access and manipulate objects within your code. It plays a crucial role in understanding and writing clean, efficient, and maintainable JavaScript code. Knowing how 'this' works can help you tackle real-world programming challenges, debug issues, and prepare for interviews.

In this lesson, we will delve deeper into the concept of 'this', explore its behavior in various scenarios, and provide practical examples to solidify your understanding.

Prerequisites

Before diving into the core concept of 'this', it is essential to have a good understanding of the following topics:

  1. Basic JavaScript syntax and variables
  2. Functions in JavaScript
  3. Objects and properties in JavaScript
  4. Callbacks, events, and closures
  5. Understanding ES6 features like arrow functions and let/const declarations

Core Concept

In JavaScript, the 'this' keyword refers to the object that is calling or containing the function where it is used. However, its value can change based on how a function is called, making it a bit tricky to understand at first. Here are some key points to remember:

  1. Global Context: When a function is called outside of any other object (i.e., not as a method), 'this' refers to the global object (in most browsers, this is the window object).
let myGlobal = "I am in the global scope";
function printGlobal() {
console.log(myGlobal);
}
printGlobal(); // Output: I am in the global scope
  1. Method Context: When a function is called as a method of an object, 'this' refers to that specific object.
let myObject = {
myProperty: "I am an object property",
printProp() {
console.log(this.myProperty);
}
};
myObject.printProp(); // Output: I am an object property
  1. Implicit Binding (call, apply, and bind methods): These methods allow you to explicitly set the value of 'this' when calling a function.
let myObject = {
myProperty: "I am an object property",
printProp() {
console.log(this.myProperty);
}
};
myObject.printProp.call({ myProperty: "I am not the original object" }); // Output: I am not the original object
  1. Arrow functions: Arrow functions do not have their own 'this'. Instead, they inherit 'this' from their parent scope.
let myObject = {
myProperty: "I am an object property",
printProp() {
console.log(this.myProperty);
}
};
let printPropArrow = () => console.log(this.myProperty); // Output: undefined (arrow functions don't have 'this')
myObject.printProp = printPropArrow;
myObject.printProp(); // Output: undefined (arrow function inherits 'this' from the parent scope, which is not myObject)
  1. Strict Mode: In strict mode, 'this' within global scope will be undefined. To enable strict mode in your scripts, add "use strict" at the beginning of your JavaScript files.
  1. ES6 Classes: When using ES6 classes, 'this' is automatically bound to the instance of the class when a method is called.
class MyClass {
constructor() {
this.myProperty = "I am a class property";
}
printProp() {
console.log(this.myProperty);
}
}
let myInstance = new MyClass();
myInstance.printProp(); // Output: I am a class property

Worked Example

Let's create a simple constructor for a Car object and use 'this' to set its properties and methods. We will also explore how 'this' behaves when using arrow functions as methods.

function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
// Regular method with 'this' bound to the Car instance
this.startEngine = function() {
console.log(`Starting engine of ${this.make} ${this.model}`);
};
// Arrow function method without its own 'this'. It will inherit 'this' from the parent scope, which is undefined in this case.
this.displayYear = () => console.log(this.year);
}
let myCar = new Car("Toyota", "Corolla", 2018);
myCar.startEngine(); // Output: Starting engine of Toyota Corolla
myCar.displayYear(); // Outputs an error, as 'this' does not have a year property in the global scope

To fix the issue with the arrow function method, we can bind 'this' using the bind() method or use an IIFE (Immediately Invoked Function Expression) to create a new scope for the callback or event handler.

Common Mistakes

  1. Forgetting to bind 'this' when using callbacks or events.
  2. Assuming that arrow functions always inherit 'this' from the parent scope, leading to unexpected results.
  3. Not understanding how 'this' behaves in for loops and map functions.
  4. Using 'this' inside a constructor without realizing it will lose its original value when the object is returned.
  5. Misusing call, apply, or bind methods without understanding their differences and proper usage.
  6. Failing to enable strict mode, leading to unexpected behavior with global 'this'.

Practice Questions

  1. Write a function printDetails that takes an object as an argument and logs its properties using 'this'. Call this function with both global and object contexts.
  2. Create a constructor for a Person object, set its properties, and add a method to calculate the person's age in years. Use 'this' appropriately.
  3. Write a function printArray that takes an array of numbers as an argument and logs each number using 'this'. Call this function with both global and object contexts.
  4. Explain the differences between call(), apply(), and bind() methods, providing examples of when to use each one.
  5. Describe how 'this' behaves in for loops and map functions compared to regular function calls, and provide solutions to avoid unexpected results.
  6. Write a simple program using ES6 classes that demonstrates the behavior of 'this' within the class context.

FAQ

Answer: Arrow functions do not have their own 'this'. Instead, they inherit 'this' from their parent scope. In this case, the parent scope is not myObject, so 'this' does not have access to its properties.

Question: How can I ensure that a callback or event handler always has access to the correct 'this' value?

Answer: You can bind 'this' using the call, apply, or bind methods when calling the function, or use an IIFE (Immediately Invoked Function Expression) to create a new scope for the callback or event handler. In ES6 classes, you can use the bind() method on the constructor to set the initial value of 'this' for instance methods.

Question: Why does 'this' behave differently in for loops and map functions compared to regular function calls?

Answer: In for loops and map functions, 'this' is bound to the loop variable (i.e., the current iteration object), not the calling context. This can lead to unexpected results if you're not careful. To avoid this, use arrow functions or bind 'this' explicitly within the loop or map function.

Question: How does strict mode affect the behavior of 'this'?

Answer: In strict mode, 'this' within global scope will be undefined. This can help prevent unexpected behavior when working with global variables and functions. To enable strict mode in your scripts, add "use strict" at the beginning of your JavaScript files.

Function this (Web Development) | Web Development | XQA Learn