DEV Community

buddha lama
buddha lama

Posted on

this in JS

Back to basics: this keyword


this represents the current execution context.
this may vary based on different scenarios

Global Context

this in the global context represents the window [browser environment]

Function Context

In a regular function, this varies based on how the function is invoked.

Note: this behaves differently for arrow functions

  1. Function as method: If the function is invoked as a method of an object. this represents the object containing the function
  2. Function as Standalone function: this represents the global context if the strict-mode is not enabled, in other case the this is undefined
const obj = {
  name: "John Doe",
  sayHello: function () {
    console.log("The name is " + this.name);
  }
};

//function as method
obj.sayHello(); // The name is John Doe

//function as standalone function
let sayHelloFn = obj.sayHello;
sayHelloFn(); // this is undefined and throws TypeError: Cannot read properties

Enter fullscreen mode Exit fullscreen mode

Constructor Context

When a function is constructed using a new keyword. this represents the object that is newly created.

/**
 * Construction Context: 
 * this keyword represents the newly created object
 */
function Person(gender) {
  this.gender = gender;
}
const person = new Person("male");
console.log(person.gender); //male 

Enter fullscreen mode Exit fullscreen mode

Event Handler

In case of the event handler, this keyword represents the element of the DOM that triggers the event

/**
 * Event handler
 */
const button = document.querySelector('button');
button.addEventListener('click', function() {
  console.log(this); // The button element that was clicked
});
Enter fullscreen mode Exit fullscreen mode

Arrow Function

Unlike the regular functions, the this value is not determined by how the function is invoked. Rather, this is determined by the context in which the function is defined. It is lexically scoped.

This difference that makes the arrow function useful is when you want to maintain this from the surrounding code.

const obj = {
  name: "OJ",
  printName() {
    console.log(this.name);
  },
  normalFunction: function () {
    return this;
  },
  arrowFunction: () => {
    return this;
  }
};

console.log(obj.printName());

/**
 * Normal function
 *  **/
//method is invoked
console.log("normalFunction:", obj.normalFunction()); // obj
//standalone function in invoked
const extNormalFunction = obj.normalFunction;
console.log("extNormalFunction:", extNormalFunction()); //global object when strict mode is off, otherwise undefined

/**
 * Arrow Function
 */
console.log("arrowFunction:", obj.arrowFunction()); //global/window object
const extArrowFunction = obj.arrowFunction;
console.log("extArrowFunction:", extArrowFunction()); //global/window object


Enter fullscreen mode Exit fullscreen mode

Top comments (0)