Sobes.tech
Junior

What is the keyword 'this'?

sobes.tech AI

Answer from AI

this is a keyword in JavaScript that refers to the object within which the current code is executing. Its value is determined by the way the function is called.

Main ways to determine this:

  • Global context: Outside of a function, this refers to the global object (window in browsers, global in Node.js).
  • Regular function call: In non-strict mode (strict mode), this also refers to the global object (or undefined if the function is called as a method of an object, but the object itself is null or undefined). In strict mode, this equals undefined.
  • Object method: If a function is called as a method of an object (i.e., via the dot operator .), this refers to the object that owns the method.
  • Constructor: When using the new operator, this refers to the newly created instance of the object.
  • Methods call(), apply(), bind(): These methods allow explicitly setting the value of this when calling a function. bind() returns a new function with this bound, while call() and apply() invoke the function with the specified this.
  • Arrow functions: Arrow functions do not have their own this. this in an arrow function is lexically inherited from the surrounding scope where it was defined.

Examples:

// Global context
console.log(this === window); // true (in browsers)

// Regular function call
function myFunction() {
  console.log(this);
}
myFunction(); // window (in non-strict mode)

// Object method
const myObject = {
  myMethod: function() {
    console.log(this);
  }
};
myObject.myMethod(); // myObject

// Constructor
function MyConstructor() {
  this.value = 10;
  console.log(this);
}
const instance = new MyConstructor(); // instance object

// call(), apply(), bind()
function greet(name) {
  console.log("Hello, " + name + "! My name is " + this.name);
}
const person = { name: "Alice" };
greet.call(person, "Bob"); // Hello, Bob! My name is Alice

greet.apply(person, ["Bob"]); // Hello, Bob! My name is Alice
const boundGreet = greet.bind(person);
boundGreet("Bob"); // Hello, Bob! My name is Alice

// Arrow function
const arrowFunction = () => {
  console.log(this);
};
arrowFunction(); // window (if defined in global scope)

Understanding how this is determined in various contexts is critical for writing correct JavaScript code.

What is the keyword 'this'? — QA / QA Automation - sobes.tech