DEV Community

Ehab Hussein
Ehab Hussein

Posted on • Edited on

The Versatile 'this' keyword

Many developers find the 'this' keyword confusing, but with a bit of practice, you can grasp its concept easily.

The 'this' keyword is specially made to point to objects, the value of the 'this' keyword is determined by how a function is called. as example if a function is called in the global context or the global scope it will point to the window object, if it is called inside an object (object's context) as a method it will point to that object.

To understand this, let's start with its behavior in the global scope:

console.log(this); // Prints the global object (window in browsers)

In the global scope, the value of the 'this' will be the global object, which makes sense because it's the surrounding context.

Now, let's consider an example where we define a global-scoped function:

const sayHello = function(name) {
  console.log(this);
};

sayHello('John'); 
Enter fullscreen mode Exit fullscreen mode

Image description

Since the function is called in the global scope it will point to the window object.

Let's attach the same function to an object, so instead of calling it globally, let's call it with our object and see how the 'this' keyword will behave:

const person = {
  firstName: "John",
  lastName: "Doe",
  sayHello: sayHello
};

console.log("----Function called with object----");
person.sayHello('Ehab');
console.log("----Function called globally----");
sayHello();
Enter fullscreen mode Exit fullscreen mode

Image description

As we said, the 'this' keyword for function 'sayHello' will look for its context. is the function called inside a context like the object literal or it is called in the global scope? and then 'this' will be assigned to the object of a context.

But not with arrow functions, since arrow functions do not have the 'this' keyword, they inherit it from the parent scope.

const person = {
  firstName: "John",
  lastName: "Doe",
  fullName: () => {
    console.log(this); // Prints the window object
    return `${this.firstName} ${this.lastName}`;
  }
};

console.log(person.fullName()); // Prints "undefined undefined"
Enter fullscreen mode Exit fullscreen mode

In the previous example, it prints the window object because the arrow function inherited the 'this' keyword from its parent scope which is the global scope. so if you need to use the 'this' keyword do not define arrow functions, just use regular functions

Top comments (0)