Skip to content

33 This Keyword

Biswajit Sundara edited this page Aug 18, 2023 · 1 revision

This keyword refers to the context in which a function is executed and can access properties/methods.

  • The value of this is determined at runtime and depends on how a function is called.

1. Global scope

  • When this is used outside of any function or object,
  • It refers to the global object.
  • In a web browser environment, the global object is usually the window object.
// {} in node env, window in browser console
console.log(this); 

// Output: Hello [object Window] (in a browser environment)
function greet() {
  console.log("Hello"); 
  console.log(this);
}
greet();
  • When greet() is called, this inside the function also refers to the global object
  • As the function is not being called as a method of any object.
  • So regular function executed directly refers to the global object for this

2. Function context

  • When a function is called as a method of an object
  • this refers to the object that the function is called on.
const obj = {
  name: "John",
  sayHello: function() {
    console.log("Hello, " + this.name);
  }
};

// Output: Hello, John
obj.sayHello(); 
  • this inside the function refers to the obj object as it's called as obj.sayHello()
  • We can add another function during run time and that will refer to the same object.
//output name, sayHello, sayHi
obj.sayHi = function(){
  console.log(this);
}
obj.sayHi();
  • So if a function is inside an object, this refers to the object.

3. Event Handlers

When a function is used as an event handler, this refers to the DOM element on which the event occurred.

const button = document.querySelector("button");
button.addEventListener("click", function() {
  console.log("Button clicked by: " + this);
});
  • this refers to the button element.

4. Constructor functions

  • When a function is used as a constructor to create new objects, this refers to the newly created object.
function Person(name) {
  this.name = name;
  console.log(this);
}
const john = new Person("John");
console.log(john.name); // Output: John
  • this inside the Person constructor refers to the newly created object john.

5. Explicit Binding

We can explicitly bind the this value to a specific object using methods like call(), apply(), or bind()

function greet() {
  console.log("Hello, " + this.name);
}

const person = { name: "John" };

greet.call(person); // Output: Hello, John
  • call() is used to invoke the greet function with this set to the person object.

6. Callback functions

  • It will print undefined for this.name
  • Because this refers to the global/window object
  • function(hobby) is not a function attached to the object, it's a call back function
  • So this will have global scope inside function(hobby)
const person = {
  name: "Bis",
  hobbies: ["read", "play", "sleep"],
  showHobbies() {
    this.hobbies.forEach(function (hobby) {
      console.log(hobby, this.name);
    });
  },
};
person.showHobbies();
  • The forEach functions accepts two arguments, the second argument is this
  • So we can fix it this way
// output : firstName: Biswajit
showHobbies() {
    this.hobbies.forEach(function (hobby) {
      console.log(this);
    }, {firstName: Biswajit});

// output all hobbies with name:Bis
showHobbies() {
    this.hobbies.forEach(function (hobby) {
      console.log(this);
    }, this);
  • We have applied this binding to the for each

Notes

  • The value of this is not determined by how or where a function is defined, but rather by how it is called at runtime.
  • We need to understand the specific context in which a function is called to correctly determine the value of this.

Clone this wiki locally