DEV Community

Cover image for Explaining ‘this’ keyword in javascript to a beginner
Alex for OpenSign

Posted on

Explaining ‘this’ keyword in javascript to a beginner

For new JavaScript developers understanding of 'this' keyword can be a really tricky affair. It is famous in a negative way for its ambiguity, changing its value depending on where and how the function is called. This article aims to clear the air around 'this' with a beginner-friendly explanation followed by some real world code examples.

What exactly is 'this' in JavaScript?
The JavaScript keyword 'this' simply refers to the object it belongs to. It may have different values depending on where it is used in your code:

  • In a method - 'this' refers to the owner object of that method.
  • Alone - 'this' refers to the global object of the context.
  • In a js function - 'this' refers to the global object.
  • In a js function (in strict mode) - 'this' is undefined.
  • In a event - 'this' refers to the element that receives the event.

Lets understand 'this' with real Code Examples:

  1. 'this' keyword in Global Context:
console.log(this); // In a browser environment 'this' keyword will refer to the global window object here.
Enter fullscreen mode Exit fullscreen mode
  1. 'this' keyword inside an Object Method:
const person = {
    name: 'Alex',
    greet: function() { console.log('Hey, my name is ' + this.name); }
};
person.greet(); // 'Hey, my name is Alex'
Enter fullscreen mode Exit fullscreen mode
  1. 'this' keyword with Constructors:
function Person(name) {
    this.name = name;
}
const personobj = new Person('Alex');
console.log(personobj.name); // 'Alex'
Enter fullscreen mode Exit fullscreen mode
  1. 'this' keyword in an Arrow Function: Arrow functions do not have their own 'this' value and that is why are more often than not used to avoid the confusion surrounding 'this' keyword.
const person = {
    name: 'Alex',
    greet: () => { console.log('Hey, my name is ' + this.name); }
};
person.greet(); // 'Hey, my name is ' + undefined
Enter fullscreen mode Exit fullscreen mode

In this example above the arrow function does not bind its own 'this' value so 'this.name' is not assigned to the person object so it falls back to the 'this' of the surrounding scope which is undefined in strict mode.

  1. 'this' keyword in Event Listeners:
document.querySelector('button').addEventListener('click', function() {
    console.log(this); // 'this' keyword refers to the button element in this case.
});
Enter fullscreen mode Exit fullscreen mode

Common Pitfalls with using 'this' keyword:
One of the most common mistakes beginners do is losing the context of 'this' while passing methods as callbacks or in setTimeout:

const person = {
    name: 'Alex',
    greet: function() { setTimeout(function() { console.log('Hello ' + this.name); }, 1000); }
};
person.greet(); // output - 'Hello undefined'
Enter fullscreen mode Exit fullscreen mode

To fix this issue you can use Function.prototype.bind() which creates a new function with 'this' bound to the current object:

const person = {
    name: 'OpenSign',
    greet: function() { 
        setTimeout(function() { 
            console.log('Hello ' + this.name); 
        }.bind(this), 1000);}
};
person.greet(); //‘Hello OpenSign’
Enter fullscreen mode Exit fullscreen mode

Using 'this' keyword with 'bind()' method , 'call()' method and 'apply()' method:
These methods can easily set the value of 'this' to control the execution context of a function as required:

  • bind() function: It creates a new function with 'this' bound to a specific object which allows you to pass it as a parameter.
  • call() function: It executes a function with in a unique way such thay 'this' is set to the first argument you pass to it.
  • apply() function: It is similar to the call() function just that it takes an array of arguments to pass to the function.
function introduce(language) {
  console.log(`I am ${this.name} and I can only code in ${language}`);
}

const dev = { name: 'Alex' };
introduce.call(dev, 'JavaScript'); // I am Alex and I can only code in JavaScript
introduce.apply(dev, ['JavaScript']); // I am Alex and I can only code in JavaScript

const boundedFunction = introduce.bind(dev);
boundedFunction('JavaScript'); // I am Alex and I can only code in JavaScript 
Enter fullscreen mode Exit fullscreen mode

Best Practices for Using ‘this’ keyword:

  • Always be very clear in advance about which object ‘this’ refers to within the function you are writing to avoid unexpected issues later.
  • Whenever in doubt use console.log(this) to check what ‘this’ refers to at a certain point in your code to debug.
  • Use .bind(thisArg), .call(thisArg, arg1, ...argN) or .apply(thisArg, [argsArray]) to explicitly set the value of ‘this’ and get your code to do what exactly you want it to do.

Common mistakes that beginners do with ‘this’ and how to avoid them :

The Mistake: Losing value of ‘this’ in Callbacks
The Solution: Use bind() to make sure that ‘this’ refers to the correct object.

The Mistake: Confusing ‘this’ with arrow functions
The Solution: Always remember that arrow functions don’t bind their own ‘this’ value.

The Mistake: Not knowing what ‘this’ refers to in event handlers.
The Solution: Simply default to using traditional function expressions for event handlers unless you are sure of the ‘this’ value.

The keyword ‘this’ is a core and important concept in JavaScript that if understood correctly, can unlock powerful patterns and help you solve complex problems with simple solutions.

Ready to start your javascript journey with open-source? Visit OpenSign on GitHub and see where open source contributions can take the project. Whether it's improving documentation, designing UI/UX, or enhancing security features, your contribution could make the next big impact.

Happy coding, and we can't wait to see the contributions you'll make!

⭐ OpenSign on GitHub

Top comments (0)