this is about this

Narendra

Narendra / May 29, 2023

2 min read––– views

In JavaScript, this keyword refers to the context in which a function is executed. The value of this can vary depending on how the function is called. Here's an overview of different scenarios for this keyword: Global context: When used outside of any function or object, this refers to the global object. In a browser, this is the window object, while in a Node.js environment, it's the global object. console.log(this); ​ Object method: When used inside an object method, this refers to the object that owns the method.

const person = {
  name: "Alice",
  greet: function() {
    console.log("Hello, my name is " + this.name);
  },
};

person.greet(); // "Hello, my name is Alice"

​ Constructor function: When a function is used as a constructor with the new keyword, this refers to the newly created instance of the object.

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

const alice = new Person("Alice");
console.log(alice.name); // "Alice"

​ Event handler: In an event handler, this usually refers to the DOM element that triggered the event.

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

document.getElementById("myButton").addEventListener("click", function() {
  console.log(this); // <button id="myButton">Click me</button>
});

​ Call, apply, and bind: When using the call, apply, or bind methods, the value of this can be explicitly set to a specific object.

const person = {
  name: "Alice",
};

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

greet.call(person); // "Hello, my name is Alice"

​ Arrow functions: Arrow functions do not have their own this context. Instead, they inherit the this value from their enclosing scope.

const person = {
  name: "Alice",
  greet: function() {
    setTimeout(() => {
      console.log("Hello, my name is " + this.name);
    }, 1000);
  },
};

person.greet(); // "Hello, my name is Alice"

​ It's important to note that the value of this can sometimes be unexpected, especially when dealing with callbacks, event handlers, or other asynchronous operations. To avoid confusion, developers often use bind, arrow functions, or assign the value of this to another variable (commonly selfor that) in order to maintain the desired context. Bindings: Default binding: to global object Implicit binding: to the object upon it is called explicit binding(hard binding): explicitly binding this to an object - using call, apply, bind constructor call binding: this refers to newly created instance of the class

Subscribe to the newsletter

Get emails from me about web development, tech, and early access to new articles.

- subscribers – View all issues