JS this Keyword Tutorial 🎯

beginner
17 min

JS this Keyword Tutorial 🎯

Welcome to CodeYourCraft's comprehensive guide on the JS this keyword! By the end of this tutorial, you'll have a solid understanding of what this is, why it's important, and how to use it in various JavaScript contexts.

Let's dive right in! 🐳

Table of Contents

  1. What is the this keyword in JavaScript?
  2. Understanding the value of this
  3. this in Global Scope
  4. this in Function Scope
  5. this in Method Scope
  6. this in Arrow Function Scope
  7. this in Objects
  8. call(), apply(), and bind() methods
  9. Common this gotchas
  10. Quiz 📝

<a name="what-is-this"></a>

1. What is the this keyword in JavaScript?

In simple terms, the this keyword in JavaScript refers to the object that a function is currently being called upon. It helps in understanding the context of a function, and is a crucial concept to grasp when working with objects and methods in JavaScript.

<a name="understanding-the-value"></a>

2. Understanding the value of this

The value of this varies depending on the execution context. Let's see how it behaves in different contexts.

<a name="global-scope"></a>

3. this in Global Scope

In the global scope, this usually refers to the window object in a browser environment.

javascript
// Global Scope console.log(this === window); // true

<a name="function-scope"></a>

4. this in Function Scope

In function scope, the value of this is determined by how the function is called.

javascript
// Function Scope function sayHello() { console.log('Hello, ' + this.name); } // If the function is called without an object context: sayHello(); // ReferenceError: name is not defined // If the function is called as a method of an object: const person = { name: 'John', sayHello }; person.sayHello(); // Hello, John

<a name="method-scope"></a>

5. this in Method Scope

In method scope, this refers to the object the method belongs to.

javascript
// Method Scope const person = { name: 'John', sayHello: function() { console.log('Hello, ' + this.name); } }; person.sayHello(); // Hello, John

<a name="arrow-function-scope"></a>

6. this in Arrow Function Scope

Arrow functions do not have their own this. Instead, this retains its original value from the enclosing context.

javascript
// Arrow Function Scope const person = { name: 'John', sayHello: () => { console.log('Hello, ' + this.name); } }; person.sayHello(); // ReferenceError: this.name is not defined // To access `this` in arrow functions, bind it explicitly: person.sayHello = () => { const that = this; console.log('Hello, ' + that.name); };

<a name="objects"></a>

7. this in Objects

In JavaScript, this can be explicitly bound to an object using the call(), apply(), or bind() methods. This allows us to call methods as if they belong to a specific object.

javascript
// Objects const person = { name: 'John', sayHello: function() { console.log('Hello, ' + this.name); } }; // Calling the method with call() person.sayHello.call({ name: 'Alice' }); // Hello, Alice // Calling the method with apply() const args = ['Alice']; person.sayHello.apply({ name: 'Alice' }, args); // Hello, Alice

<a name="call-apply-bind"></a>

8. call(), apply(), and bind() methods

These methods are used to explicitly set the value of this for a function call.

  • call(): Calls a function with a specified this value and arguments provided as individual arguments.
  • apply(): Calls a function with a specified this value and arguments provided as an array.
  • bind(): Creates a new function with a specified this value and pre-sets its arguments. The new function can be invoked at a later time.

<a name="gotchas"></a>

9. Common this gotchas

  • this in event listeners: Event listeners can sometimes lead to unexpected this values. To avoid this, use arrow functions or bind this explicitly.
javascript
// Event listener example const button = document.getElementById('myButton'); button.addEventListener('click', function() { console.log('Button clicked!', this); });
  • Inheritance and this: When inheriting from a constructor function, this might not behave as expected. To avoid confusion, bind this explicitly within the constructor.

<a name="quiz"></a>

10. Quiz 📝

Quick Quiz
Question 1 of 1

What is the value of `this` when a JavaScript function is called in the global scope?

That wraps up our comprehensive guide on the JS this keyword! By now, you should have a solid understanding of this and its importance in JavaScript. Happy coding! 💻🚀