JavaScript Core Concepts | Execution Context and this

Luisa Novaes - Aug 25 - - Dev Community

3. Execution Context and this

  • Question: Explain how it works and how the value of this is determined in different scenarios.
    • this refers to the object of the context, and its value depends on how a function is called:
      • In the global context, outside of any function: this refers to the global object (e.g., window in the browser).
      • Inside a method: this refers to the object that owns the method.
      • In DOM events: this refers to the element that triggered the event.
      • With call, apply, or bind: you can explicitly set the value of this.

Examples:

  1. Global Context
console.log(this); // In the browser, this will log the global object `window`
Enter fullscreen mode Exit fullscreen mode
  1. Inside a Method
const person = {
  name: 'John',
  greet: function() {
    console.log(this.name); // `this` refers to the `person` object
  }
};

person.greet(); // Output: John
Enter fullscreen mode Exit fullscreen mode
  1. In DOM Events
<button id="myButton">Click me</button>
<script>
  document.getElementById('myButton').addEventListener('click', function() {
    console.log(this); // `this` refers to the button element that triggered the event
  });
</script>
Enter fullscreen mode Exit fullscreen mode
  1. Using call, apply, or bind
function greet() {
  console.log(`Hello, ${this.name}`);
}

const person = { name: 'Jane' };

greet.call(person); // Output: Hello, Jane

greet.apply(person); // Output: Hello, Jane

const boundGreet = greet.bind(person);
boundGreet(); // Output: Hello, Jane
Enter fullscreen mode Exit fullscreen mode
. . . . . .
Terabox Video Player