Skip to content

JavaScript this Keyword

  • by

The this keyword in JavaScript is a special keyword that refers to the current execution context or the object that a function is bound to when it’s invoked. The value of this is determined dynamically at runtime and can vary depending on how a function is called.

Here are some common use cases and rules for determining the value of this:

1. Global Scope: In the global scope (outside of any function), this refers to the global object, which is window in a web browser or global in Node.js.

console.log(this); // Refers to the global object (e.g., `window` in a web browser)

2. Function Invocation: When a function is invoked as a standalone function (not as a method of an object or constructor), this still refers to the global object. However, if you are using strict mode ("use strict"), this will be undefined in such cases.

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

myFunction(); // Refers to the global object (or `undefined` in strict mode)

3. Method Invocation: When a function is called as a method of an object, this refers to the object on which the method is being called. The object becomes the context of the function, and you can access its properties and methods using this.

const obj = {
  name: 'John',
  sayHello: function() {
    console.log(this.name);
  }
};

obj.sayHello(); // Refers to the `obj` object and logs 'John'

4. Constructor Invocation: When a function is used as a constructor function with the new keyword, this refers to the newly created object. Inside the constructor function, you can assign properties and methods to this, which will be accessible from the newly created object.

function Person(name) {
  this.name = name;
  console.log(this);
}

const person = new Person('Alice'); // Refers to the newly created object (`person`)

5. Event Handlers: In event handler functions, such as those used with HTML elements, this refers to the element that triggered the event.

<button id="myButton">Click Me</button>

<script>
  const button = document.getElementById('myButton');
  button.addEventListener('click', function() {
    console.log(this); // Refers to the button element
  });
</script>

6. Explicit Binding: You can explicitly bind the value of this using methods like call(), apply(), or bind(). These methods allow you to specify the value of this explicitly, overriding the default behavior.

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

const person = { name: 'Alice' };

greet.call(person); // Refers to the `person` object and logs 'Hello, Alice!'
greet.apply(person); // Same as `call()`, but accepts arguments as an array
const boundGreet = greet.bind(person);
boundGreet(); // Creates a new function bound to the `person` object and logs 'Hello, Alice!'

Important Note: the actual value of this depends on the specific context in which the function is called. Understanding the invocation context is crucial to correctly use and interpret the value of this in your JavaScript code.

JavaScript this Keyword example

Certainly! Here’s an example that demonstrates the usage of the this keyword in different contexts:

<!DOCTYPE html>
<html>
<head>
  <title>JavaScript this Keyword Example</title>
</head>
<body>
  <button id="myButton">Click Me</button>

  <script>
    // Global Scope
    console.log(this); // Refers to the global object (e.g., `window` in a web browser)

    // Function Invocation
    function greet() {
      console.log(`Hello, ${this.name}!`);
    }

    const person = {
      name: 'Alice',
      greet: greet
    };

    greet(); // Refers to the global object and logs 'Hello, undefined!'
    person.greet(); // Refers to the `person` object and logs 'Hello, Alice!'

    // Method Invocation
    const calculator = {
      value: 0,
      add: function(num) {
        this.value += num;
      },
      subtract: function(num) {
        this.value -= num;
      },
      getResult: function() {
        console.log(this.value);
      }
    };

    calculator.add(5);
    calculator.subtract(3);
    calculator.getResult(); // Refers to the `calculator` object and logs '2'

    // Constructor Invocation
    function Person(name) {
      this.name = name;
    }

    const john = new Person('John');
    console.log(john.name); // Logs 'John'

    // Event Handlers
    const button = document.getElementById('myButton');
    button.addEventListener('click', function() {
      console.log(this); // Refers to the button element
    });

    // Explicit Binding
    function saySomething(message) {
      console.log(`${message}, ${this.name}!`);
    }

    const alice = { name: 'Alice' };

    saySomething.call(alice, 'Hello'); // Refers to the `alice` object and logs 'Hello, Alice!'
    saySomething.apply(alice, ['Hi']); // Same as `call()`, but accepts arguments as an array

    const boundFunction = saySomething.bind(alice, 'Hey');
    boundFunction(); // Creates a new function bound to the `alice` object and logs 'Hey, Alice!'
  </script>
</body>
</html>

Output:

JavaScript this Keyword

Comment if you have any doubts or suggestions on this Js keyword topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading